python-3.x - Python __getattribute__ 与 'is-a'/'has-a' 关系
问题描述
使用 python3 我有点困惑为什么__getattribute__
不使用我的类结构。我用谷歌搜索,但不明白为什么它不起作用。
这是简洁的类结构,删除了所有不需要的内容:
class Platform:
def execute(self):
print("Calling execute in Platform")
class Host():
def __init__(self):
self.plat = Platform()
def __getattr__(self, name):
if name in dir(self):
return self.__getattribute__(name)
if name in dir(self.plat):
return self.plat.__getattribute__(name)
class Connector(Host):
pass
class LDAP():
def __init__(self):
self.conn = Connector()
def __getattr__(self, name):
return self.conn.__getattribute__(name)
我有一个工作对象ldp = LDAP()
。跟注ldp.execute()
加注AttributeError: 'Connector' object has no attribute 'execute'
我希望调用ldp.execute()
会执行以下操作:
- 调用对象
__getattr__
的LDAP
调用__getattribute__
_Connector
- 那会再次调用
__getattr__
哪个Host
会__getattribute__
调用Platform
对象 - 那最终会
execute
从Platform
当然,这并没有按预期工作:)
但是,如果我在 LDAP 类中调用self.conn.__getattr__(name)
,__getattr__
那会起作用,可能是因为我__getattr__
在 Host 中定义了。
我在这里想念什么?
注意:我无法修改 Platform 和 Host 类。只有连接器和 LDAP 是我的
解决方案
直接调用通常是错误的__getattribute__
。相反,使用getattr
内置:
class LDAP():
def __init__(self):
self.conn = Connector()
def __getattr__(self, name):
return getattr(self.conn, name)
该getattr
函数知道要查找__getattr__
,而不知道__getattribute__
。
推荐阅读
- c# - 如何在 C# 中将流代码转换为 observable(reactive)?
- twitter - 在 Vaadin 14.2 应用程序中使用 pac4j 通过 Twitter 进行身份验证:“code”:32,“message”:“无法对您进行身份验证。”
- c# - Windows 10 上的 winforms 应用程序的触摸屏键盘问题
- python - 我正在尝试学习 python,但我的代码不起作用,我不知道为什么
- ngxs - 使用动作处理程序时,Ngxs 未完全等待动作成功解析
- android - 为什么有些项目会导入 androidx.activity-ktx?
- html - 如果通过脚本设置值,则 datetime-local 上的输入不起作用
- java - 在 Ant 构建中将 zip64Mode 设置为“始终”后,它显示错误:运行 java 程序时无法找到或加载主类
- python - 从 Github 下载的项目设置错误
- python - 如何使用 Python 禁用或启用 windows shield?