Python从父静态方法调用子静态变量

标签 python

我基本上如何做到这一点?

class Parent:
    Foo = 'Parent food'

    @staticmethod
    def bar():
        # want to print whatever the child's Foo is


class Child(Parent):
    Foo = 'Child foo'


# This should print "Child foo"
Child.bar() 

最佳答案

您可以使用类方法来实现

class Parent:
    Foo = 'Parent food'

    @classmethod
    def bar(cls):
        print cls.Foo

class Child(Parent):
    Foo = 'Child foo'


Child.bar()
# This will print "Child foo"

关于Python从父静态方法调用子静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42020378/

相关文章:

php - 服务器端推送的可扩展解决方案?

python - 在 url 模式中使用 include() 时出现意外的 NoReverseMatch 错误

python - 当条件为非 bool 值时,如何在列表理解中使用 "else"?

python - Django 1.9.1 prefetch_related 仅多次命中数据库

python - 从 'BlobServiceClient' 导入 'azure.storage.blob' 时出错

python - Matplotlib 在给定 csv 数据的情况下创建曲面图 (x,y,z,color) - 颜色错误

python - 使用 Python 请求 : Sessions, Cookie 和 POST

Python,循环打开文件(dicom)

python - 在树递归期间保存路径

python - 如何将字符串格式化为两列列表