具有以下课程:
class Human:
def __init__(self):
self.age = 0
human = Human()
print(human.age) # 0
想要类似以下魔术方法的方法。这种魔术方法将使我有机会在返回之前处理被调用的变量。
class Human:
def __init__(self):
self.age = 0
def __variable_handler__(self, attribute_name):
print(self, attribute_name) # Human instance, 'age'
human = Human()
print(human.age) # 0
您能帮助我,并在Python中提示如何实现它吗?
答案 0 :(得分:1)
我认为您可以使用__getattribute__
方法来实现。
代码如下:
class Human:
def __init__(self):
self.age = 0
def __getattribute__(self, attribute_name):
print(self, attribute_name)
try:
return super(Human, self).__getattribute__(attribute_name)
except AttributeError:
return None
human = Human()
print(human.age)
输出为:
<__main__.Human object at 0x11bfa0ef0> age
0