首页 > 解决方案 > 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()会执行以下操作:

当然,这并没有按预期工作:)

但是,如果我在 LDAP 类中调用self.conn.__getattr__(name)__getattr__那会起作用,可能是因为我__getattr__在 Host 中定义了。

我在这里想念什么?

注意:我无法修改 Platform 和 Host 类。只有连接器和 LDAP 是我的

标签: python-3.x

解决方案


直接调用通常是错误的__getattribute__。相反,使用getattr内置:

class LDAP():
  def __init__(self):
    self.conn = Connector()

  def __getattr__(self, name):
    return getattr(self.conn, name)

getattr函数知道要查找__getattr__,而不知道__getattribute__


推荐阅读