【问题标题】:Python How to override a class member in the child and access it from parent?Python如何覆盖子类中的类成员并从父类访问它?
【发布时间】:2013-10-19 14:24:11
【问题描述】:

所以在 Python 中我有一个这样的类:

class Parent(object):
    ID = None

    @staticmethod
    def getId():
        return Parent.ID

然后我在子类中覆盖 ID,如下所示:

class Child(Parent):
    ID = "Child Class"

现在我想调用孩子的getId()方法:

ch = Child()
print ch.getId()

我现在想看“儿童班”,但我得到的是“无”。
我怎样才能在 Python 中实现这一点?

PS:我知道我可以直接访问ch.ID,所以这可能更像是一个理论问题。

【问题讨论】:

    标签: python class inheritance


    【解决方案1】:

    使用类方法:

    class Parent(object):
        ID = None
    
        @classmethod
        def getId(cls):
            return cls.ID
    
    class Child(Parent):
        ID = "Child Class"
    
    print Child.getId() # "Child Class"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-13
      • 2011-11-03
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多