Python:检测重新定义?

发布于 2024-12-07 13:09:44 字数 108 浏览 1 评论 0原文

我正在寻找一种方法来检测 python 函数或类是否正在被重新定义,或者即使它被定义了两次并且一个定义删除了另一个定义。
这可以通过反射来完成吗?
也许是通过函数(或类)本身以某种方式?

I'm looking for a way to somehow detect if a python function or class is being redefined or even only if it is defined twice and one definition erases the other.
Can this be done with reflection somehow?
Maybe by the function (or class) itself somehow?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落叶缤纷 2024-12-14 13:09:44

类的重新定义对原始类没有任何作用,它只是将一个全新的类分配给相同的名称。检查很简单 - 只需保存原始文件,然后查看该名称是否仍然引用它即可。

class SomeClass(object):
    x = 1

# Save the original
_my_saved_class = SomeClass

class SomeClass(object):
    x = 2

# Check if they're the same!
if SomeClass is not _my_saved_class:
    print "SomeClass was redefined!"

Redefinition of a class does nothing to the original class, it just assigns a whole new class to the same name. Checking is easy – just save the original, and see if the name still refers to it.

class SomeClass(object):
    x = 1

# Save the original
_my_saved_class = SomeClass

class SomeClass(object):
    x = 2

# Check if they're the same!
if SomeClass is not _my_saved_class:
    print "SomeClass was redefined!"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文