【问题标题】:Using the child's static variable in a parent's static method在父静态方法中使用子静态变量
【发布时间】:2019-09-14 23:03:09
【问题描述】:

我目前正在尝试抽象/默认一些行为。所有孩子都以不同的方式定义了一些常量,我想在他们的父类中引用所述变量。我的尝试看起来像这样:

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 中的继承中您不会覆盖变量,而只是将它们隐藏在视野之外?

【问题讨论】:

    标签: python-3.x static-methods


    【解决方案1】:

    Child 类中,当something 被调用时,Mother.a 仍然有效,您指的是父类Mother(在Childs 类声明中定义)。 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
    

    来自文档:

    类方法不同于 C++ 或 Java 静态方法。如果你想要这些,请参阅 staticmethod()。

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

    我推荐this video 以获得关于类的最佳实践以及如何/在哪里使用 python 中所有特殊装饰器/语法的精彩介绍。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多