gpt4 book ai didi

Python Metaclass 使用时没有改变类

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:15 32 4
gpt4 key购买 nike

我在搜索元类在 python 中的用法时发现了这个问题。这是一个很好的问题和一个很好的答案,See Here .但是当我按照这样的例子进行操作时:

class UpperAttrMetaclass(type): 

def __new__(cls, name, bases, dct):

attrs = ((name, value) for name, value in dct.items() if not name.startswith('__'))
uppercase_attr = dict((name.upper(), value) for name, value in attrs)

return type.__new__(cls, name, bases, uppercase_attr)
class Foo(object):
__metaclass__=UpperAttrMetaclass
bar = 'bip'

然后:

print(hasattr(Foo,'bar'))

我希望它会输出False,但结果却是True似乎元类根本没有改变任何东西。我一定是弄错了。很高兴你能指出来!

编辑:我正在使用 IDLE 3.2,以使我的情况更清楚。

编辑:感谢所有的答案。我找到了一篇关于这个的好帖子。所以我把它贴在这里 Metaclass in python 2&3

最佳答案

你没有弄错。 print(hasattr(Foo,'bar'))print dir(Foo) 给我:

False
['BAR', '__class__', ...

你的 Python 版本是多少?我的是 2.7.2

如果您使用 Python 3.x,请尝试删除 __metaclass__ 属性并将您的类声明为

class Foo(object, metaclass=UpperAttrMetaclass):
...

关于Python Metaclass 使用时没有改变类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9254991/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com