Python 如何覆盖子类中的类成员并从父类访问它?

标签 python class inheritance

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

class Parent(object):
    ID = None

    @staticmethod
    def getId():
        return Parent.ID

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

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

现在我要调用child的getId()方法:

ch = Child()
print ch.getId()

我现在想看到“子类”,但我得到的却是“无”。
我怎样才能在 Python 中实现它?

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

最佳答案

使用类方法:

class Parent(object):
    ID = None

    @classmethod
    def getId(cls):
        return cls.ID

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

print Child.getId() # "Child Class"

关于Python 如何覆盖子类中的类成员并从父类访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19467099/

相关文章:

python - 传递列表时出现类型错误 (Python)

PHP OOP 数据库连接

c++ - 一个基类的多重继承

python - 姿势之间的相对旋转 (rvec)

javascript - 下载 javascript 加载的页面

javascript - 在 python 输出中删除 `u` 字符

javascript - ROR + 从文本字段中检测类名并将其替换为另一个

c++ - 字体渲染函数 C++ SDL 中未处理的异常

java - 泛型和继承

Java 泛型不能对泛型 T 使用通配符