Gni*_*ohz 3 python metaprogramming python-3.x
当我在python中搜索元类的用法时,我发现了这个问题.这是一个很好的问题,有一个很好的答案,请看这里.但是我按照这样的例子:
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'
Run Code Online (Sandbox Code Playgroud)
然后:
print(hasattr(Foo,'bar'))
Run Code Online (Sandbox Code Playgroud)
我希望它会输出False,但相反True
它似乎是元类没有改变任何东西.我一定是犯了一个错误.很高兴你能指出我的意思!
编辑:我正在使用IDLE 3.2,以使我的情况更加清晰.
编辑:谢谢你的所有答案.我在这里发现了一个很好的帖子.所以我在这里发布它在python 2和3中的元类
你没有犯错.print(hasattr(Foo,'bar'))并print dir(Foo)告诉我:
False
['BAR', '__class__', ...
Run Code Online (Sandbox Code Playgroud)
你的Python版本是什么?我的是2.7.2
如果您使用Python 3.x,请尝试删除该__metaclass__属性并将您的类声明为
class Foo(object, metaclass=UpperAttrMetaclass):
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
149 次 |
| 最近记录: |