因此,假設我想寫我自己的類,重寫__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 *。 –