在 parent 的静态方法中使用 child 的静态变量

Using the child's static variable in a parent's static method

我目前正在尝试 abstract/default 消除一些行为。所有 children 都以不同方式定义了一些常量,我想在它们的 parent class 中引用所述变量。我的尝试看起来像这样:

class Mother():
    a= True

    @staticmethod
    def something():
        return Mother.a


class Child(Mother):
    a = False


print(Mother.something())
print(Child.something())

Mother.something() 显然会产生 True,但 Child.something() 应该产生 False.

这不起作用,因为我猜想在 Python 的继承中,您没有覆盖变量,只是将它们隐藏在视野之外?

Childclass中,调用something时,Mother.a仍然有效,你指的是父Motherclass(在 Childs class 声明中定义)。 Python 有另一个名为 classmethod 的内置函数用于您的用例:

class Mother():
    a = True

    @classmethod
    def something(cls):
        return cls.a

class Child(Mother):  # Mother.a gets defined here
    a = False

print(Mother.something())  # True
print(Child.something())  # False

来自文档:

Class methods are different than C++ or Java static methods. If you want those, see staticmethod().

@classmethods 定义 cls(按照惯例,变量不必被称为 cls)作为第一个参数,就像实例方法将接收 self 作为他们的第一个参数。 cls 指的是正在调用该方法的 class。

我建议 this video 详细介绍 classes 和 how/where 使用 python 中所有特殊 decorators/syntax 的最佳实践.

既然你提到了抽象 classes,你可能也对 abc 模块感兴趣。