python3元类_python 3.x 中的元类

下面这段代码是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__)

展开

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值