因此,假设我想写我自己的类,重写__getattribute__
函数。每当有人调用未定义的属性时,我都希望它生成一个随机int。获取关于没有__dict__或dir()的定义属性的信息
X = GetAttribute()
print(X.predefined_attribute) # "First attribute"
X.attr2 = "Hi"
print(X.attr2) # "Hi"
print(X.attr3) # random int
显然,我不能写这样的东西,因为它会导致递归。
class GetAttribute(object):
def __init__(self):
self.predefined_attribute = "First attribute"
def __getattribute__(self, attr):
if attr not in self.__dict__: # the bad line
return randint(0, 9999)
else:
return object.__getattribute__(self, attr)
我如何不使用__dict__
,可以获取有关定义属性的信息?
你的递归是由所有属性必须生活在'__dict__'假设引起的。你应该首先检查* class *。 –