0
我有以下代碼,它來自O'Reilly Media出版的Learning Python。爲什麼第3行(self._name = name
)不會觸發__getattribute__
?是否因爲__setattr__
覆蓋它?__setattr__可以覆蓋Python中的__getattribute__嗎?
class Person: # Portable: 2.X or 3.X
def __init__(self, name): # On [Person()]
self._name = name # Triggers __setattr__!
def __getattribute__(self, attr): # On [obj.any]
print('get: ' + attr)
if attr == 'name': # Intercept all names
attr = '_name' # Map to internal name
return object.__getattribute__(self, attr) # Avoid looping here
def __setattr__(self, attr, value): # On [obj.any = value]
print('set: ' + attr)
if attr == 'name':
attr = '_name' # Set internal name
self.__dict__[attr] = value # Avoid looping here
您不需要獲取要設置它的屬性。 – user2357112