3 回答
TA贡献1815条经验 获得超6个赞
__getattr____getattribute____getattr__
__getattribute__
object__getattr____getattribute__.
__getattr__.
TA贡献1852条经验 获得超7个赞
__getattr____getattribute__
__getattr__
__getattr____getattr__obj1.myminobj1.mymaxobj1.mycurrentAttributeError: '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贡献1890条经验 获得超9个赞
__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
添加回答
举报
