3 回答

TA贡献1982条经验 获得超2个赞
__getattr__
__getattribute__
__getattr__
__getattribute__
object
__getattr__
__getattribute__
.
__getattr__
.

TA贡献1801条经验 获得超8个赞
__getattr__
__getattribute__
__getattr__
__getattr__
__getattr__
obj1.mymin
obj1.mymax
obj1.mycurrent
AttributeError: 'Count' object has no attribute 'mycurrent'
class Count(): def __init__(self,mymin,mymax): self.mymin=mymin self.mymax=mymax obj1 = Count(1,10)print(obj1.mymin)print(obj1.mymax)print(obj1.mycurrent) --> AttributeError: 'Count' object has no attribute 'mycurrent'
__getattr__
obj1.mycurrent
__getattr__
class Count: def __init__(self,mymin,mymax): self.mymin=mymin self.mymax=mymax def __getattr__(self, item): self.__dict__[item]=0 return 0obj1 = Count(1,10)print(obj1.mymin)print(obj1.mymax)print(obj1.mycurrent1)
__getattribute__
__getattribute__
__getattribute__
__getattribute__
AttributeError
class Count: def __init__(self,mymin,mymax): self.mymin=mymin self.mymax=mymax self.current=None def __getattribute__(self, item): if item.startswith('cur'): raise AttributeError return object.__getattribute__(self,item) # or you can use ---return super().__getattribute__(item)obj1 = Count(1,10)print(obj1.mymin)print(obj1.mymax)print(obj1.current)
__getattribute__
object.__getattribute__(self, name)
super().__getattribute__(item)
self.__dict__[item]
重要
__getattribute__
__getattribute__
AttributeError
__getattr__
class Count(object): def __init__(self,mymin,mymax): self.mymin=mymin self.mymax=mymax self.current=None def __getattr__(self, item): self.__dict__[item]=0 return 0 def __getattribute__(self, item): if item.startswith('cur'): raise AttributeError return object.__getattribute__(self,item) # or you can use ---return super().__getattribute__(item) # note this class subclass objectobj1 = Count(1,10)print(obj1.mymin)print(obj1.mymax)print(obj1.current)

TA贡献1785条经验 获得超8个赞
__getattr__
class Foo(object): def __getattr__(self, attr): print "looking up", attr value = 42 self.__dict__[attr] = value return value f = Foo()print f.x #output >>> looking up x 42f.x = 3print f.x #output >>> 3print ('__getattr__ sets a default value if undefeined OR __getattr__ to define how to handle attributes that are not found')
__getattribute__
RuntimeError: maximum recursion depth exceeded while calling a Python object
添加回答
举报