为什么调用 __getattr__ 而不是捕获 AttributeError?
Why __getattr__ is called instead of catching AttributeError?
我在 Python class:
中实现了一个简单的惰性初始化
class Base:
def __init__(self):
pass
def __getattr__(self, item):
print('__getattr__ was called!')
class Derived(Base):
def GetValue(self):
try:
return self.val
except AttributeError:
self.val = 1
return self.val
obj = Derived()
print(obj.GetValue())
我想在调用 GetValue() 方法时捕获 AttributeError。在这个例子中它没有发生,一个方法 getattr 被调用。 Base class 中的方法 getattr() 是强制性的,我不能放弃使用它。如果可能的话,我也不想放弃使用 try-except 块。 Python 2.7 中这个问题的解决方案是什么?
如果您无法退出使用 __getattr__
方法,您必须手动抛出异常。
class Base:
def __init__(self):
pass
def __getattr__(self, item):
print('__getattr__ was called!')
if not hasattr(self, item):
raise AttributeError(self.__class__.__name__ +
" instance has no attribute '" + item + "'")
class Derived(Base):
def GetValue(self):
try:
return self.val
except AttributeError:
self.val = 1
return self.val
obj = Derived()
print(obj.GetValue())
我在 Python class:
中实现了一个简单的惰性初始化class Base:
def __init__(self):
pass
def __getattr__(self, item):
print('__getattr__ was called!')
class Derived(Base):
def GetValue(self):
try:
return self.val
except AttributeError:
self.val = 1
return self.val
obj = Derived()
print(obj.GetValue())
我想在调用 GetValue() 方法时捕获 AttributeError。在这个例子中它没有发生,一个方法 getattr 被调用。 Base class 中的方法 getattr() 是强制性的,我不能放弃使用它。如果可能的话,我也不想放弃使用 try-except 块。 Python 2.7 中这个问题的解决方案是什么?
如果您无法退出使用 __getattr__
方法,您必须手动抛出异常。
class Base:
def __init__(self):
pass
def __getattr__(self, item):
print('__getattr__ was called!')
if not hasattr(self, item):
raise AttributeError(self.__class__.__name__ +
" instance has no attribute '" + item + "'")
class Derived(Base):
def GetValue(self):
try:
return self.val
except AttributeError:
self.val = 1
return self.val
obj = Derived()
print(obj.GetValue())