【问题标题】:The self.__dict__ dict in parent does not have child attributes?父级中的 self.__dict__ dict 没有子属性?
【发布时间】:2012-03-14 12:22:36
【问题描述】:

我有两个班级:

class Base(object):
  def __init__(self):
    object.__init__(self)

  def print_methods(self):
    print self.__dict__

class Child(Base):
   def __init__(self):
     Base.__init__(self)

   def another_method(self):
     pass

现在我可以在Child 实例中调用print_method,并期待看到another_method。但是失败了。

【问题讨论】:

    标签: python inheritance


    【解决方案1】:

    这根本与继承无关。 Child.another_method()是类的属性,不是实例,所以不在self__dict__中,而是在Child的dict中。如果您只创建Base 的实例并在此实例上调用print_methods(),您也不会看到print_methods

    要查找实例的所有方法,您可以使用dir()inspect.getmembers()(可以与callable() 结合使用以仅包含可调用属性)。

    【讨论】:

      猜你喜欢
      • 2011-11-21
      • 1970-01-01
      • 2019-12-02
      • 2016-11-12
      • 1970-01-01
      • 2017-12-20
      • 2017-12-29
      • 2011-03-29
      • 2011-11-06
      相关资源
      最近更新 更多