【问题标题】:Python: change parent class property from child classPython:从子类更改父类属性
【发布时间】:2017-08-16 14:32:32
【问题描述】:

在 python (v3.6.1) 中,我正在寻找这样的类:

class SecondClass(FirstClass):
    property = "custom"

print(SecondClass.name) #=> "john"

class SecondClass(FirstClass):
    property = "notcustom"

print(SecondClass.name) #=> "steve"

我尝试像这样设置FirstClass 类:

class FirstClass:
    if property == "custom":
        name = "john"
    else:
        name = "steve"

但我似乎无法从 SecondClass 编辑 FirstClass 的属性。

这可能吗?

【问题讨论】:

  • 你用的是什么 Python 版本?
  • 我已将版本添加到问题中(它是 3.6.1)
  • initself 部分丢失,请打开任何 python 模块获取语法,将指导您。

标签: python class syntax


【解决方案1】:

由于您使用的是 Python 3.6,因此您可以使用新的 __init_subclass__ 方法完成您的要求。来自__init_subclass__的文档:

只要包含的类被子类化,就会调用此方法。 cls 是新的子类。如果定义为普通的实例方法,则该方法隐式转换为类方法。

class FirstClass:
    def __init_subclass__(cls):
        super().__init_subclass__()
        if cls.property == "custom":
            cls.name = "john"
        else:
            cls.name = "steve"

class SecondClass(FirstClass):
    property = "custom"

print(SecondClass.name)

class SecondClass(FirstClass):
    property = "notcustom"

print(SecondClass.name) 

对于适用于 Python 3.5 及更低版本的方法,您可以使用一些 Meta 类魔法:

class FirstClass(type):
    def __init__(cls, name, bases, attrs):
        if cls.property == "custom":
            cls.name = "john"
        else:
            cls.name = "steve"
        super(FirstClass, cls).__init__(name, bases, attrs)

class SecondClass(metaclass=FirstClass):
    property = "custom"

print(SecondClass.name)

class SecondClass(metaclass=FirstClass):
    property = "notcustom"

print(SecondClass.name)

【讨论】:

    【解决方案2】:

    @classmethod 可能是您最好的选择。

    class First:
        @classmethod
        def name(cls):
            return "john" if cls.prop() == "custom" else "steve"
    
    class Second(First):
        @classmethod
        def prop(cls):
            return "custom"
    
    print(Second.name()) # -> john
    
    class Second(First):
        @classmethod
        def prop(cls):
            return "notcustom"
    
    print(Second.name()) # -> steve
    

    (另外,不要使用property,因为这已经是语言中的关键字

    【讨论】:

    • +1 表示指针和注释 property 是 python 中的关键字,但 @Christian Dean 的回答正是我所追求的
    猜你喜欢
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 2013-12-24
    相关资源
    最近更新 更多