在下面的代码中,我们尝试重载点运算符。
我不确定如何从子类内部定义的
__getattr__
方法内部的超类中调用__getattr__
。
class Floor:
def __init__(this_floor, surface_area:float):
this_floor._surface_area = float(surface_area)
class DrSeussHouse:
def __init__(this_hoos, original_year_built:int, original_floor:Floor):
this_hoos._floor = str(original_floor)
this_hoos._year_built = int(original_year_built)
def __getattr__(this_hoos, attr_name:str):
# HELP IS DESIRED RIGHT HERE, INSIDE OF...
# ... THIS IMPLEMENTATION OF `__getattr__`
# return getattr(this._wahoos._floor, attr_name)
# return getattr(super(type(this_hoos)), attr_floor)(attr_floor)
# super().__getattr__(this._wahoos._floor, attr_name)
__getattr__
仅在正常的属性查找过程失败时调用。
__getattribute__
是用于定义属性查找过程的方法,它像任何其他方法一样通过 super
调用。
def __getattribute__(self, attr_name: str):
return super().__getattribute__(attr_name)
如果你真的只想将失败的查找委托给另一个对象,你不需要
super
,__getattr__
是重载的正确方法。
def __getattr__(self, attr_name: str):
return getattr(self._wahoos._floor, attr_name)
# getattr() is preferable to
# return self._wahoos._floor.__getattr__(attr_name)