什么是错的代码?
class Spam(object):
def __init__(self, a, b):
self.a = a
self.b = b
# using this to mark field "c" as deprecated. As per my understanding this gets called only for fields that do not exist.
def __getattr__(self, c):
print("Deprecated")
# using this to manipulate the value before storing
def __setattr__(self, name, value):
self.__dict__[name] = value + 1
# interceptor to allows me to define rules for whenever an attribute's value is accessed
def __getattribute__(self, name):
return self.__dict__[name]
spam = Spam(10, 20)
print(spam.a)
print(spam.b)
print(spam.c)
但上面的代码不会打印出任何东西。请告诉我错在这里,任何人都可以帮助我理解?我读到的https://rszalski.github.io/magicmethods/#access这些方法
但上面的代码不会打印任何东西
错误。它崩溃了无限递归。
在__getattribute__
,当你想记录/截取呼叫,在某些时候,你仍然希望得到原来的方法来获得属性。和self.__dict__[name]
调用__getattribute__
所以它没有这样做的正确方法。
什么你又试图调用此方法,你会得到无限递归。调用父/基方法代替:
# interceptor to allows me to define rules for whenever an attribute's value is accessed
def __getattribute__(self, name):
return object.__getattribute__(self,name) # or super(Spam,self).__getattribute__(name)
该打印:
11
21
Deprecated
None
None
由__getattr__
返回(因为它只是打印到控制台,并含蓄地返回None
)。也许一个例外会是一个更好的主意。