[英]Python: overloading the __getattr__ and properties, making __setattr__ work correctly
[英]Python: __setattr__ operator overloading
我做了一个Poly类,它对多项式执行不同的重载运算。
如果尝试将新属性添加到多项式对象(通过定义新属性或重新绑定现有属性),我想提出一个AssertionError。
我将如何在setattr中做到这一点?
您也可以尝试使用slot功能-它将引发属性错误
class Test(object):
__slots__ = ['var']
def __init__(self, n):
self.var = n
y = Test(1)
print y.var
y.var = 2
print y.var
y.z = 4
print y.z
class CONST(object):
FOO = 1234
def __setattr__(self, *_):
raise AssertionError
const = CONST()
print const.FOO # 1234
const.FOO = 4321 # AttributeError
这是你需要的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.