下面这段代码是2.x的,虽然在3.x中也能运行格式却看不懂我看手册3.x的元类应该是这样classTest(metaclass=MyMetaClass):pass所以下面这段代码完全看不懂能不能帮我用3.x的语法写出来de...
下面这段代码是2.x的 ,虽然在3.x中也能运行 格式却看不懂
我看手册 3.x的元类应该是这样 class Test(metaclass=MyMetaClass): pass
所以下面这段代码完全看不懂 能不能帮我用3.x的语法写出来
def no_new_attributes(wrapped_setattr):
""" raise an error on attempts to add a new attribute, while
allowing existing attributes to be set to new values.
"""
def __setattr__(self, name, value):
if hasattr(self, name): # not a new attribute, allow setting
wrapped_setattr(self, name, value)
else: # a new attribute, forbid adding it
raise AttributeError("can't add attribute %r to %s" % (name, self))
return __setattr__
class NoNewAttrs(object):
""" subclasses of NoNewAttrs inhibit addition of new attributes, while
allowing existing attributed to be set to new values.
"""
# block the addition new attributes to instances of this class
__setattr__ = no_new_attributes(object.__setattr__)
class __metaclass__(type):
" simple custom metaclass to block adding new attributes to this class "
__setattr__ = no_new_attributes(type.__setattr__)
展开