Python:从子类更改父类属性

2024-06-16 13:14:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在python(v3.6.1)中,我希望编写这样的类:

class SecondClass(FirstClass):
    property = "custom"

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

class SecondClass(FirstClass):
    property = "notcustom"

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

我尝试过这样设置FirstClass类:

^{pr2}$

但我似乎无法从第二个类编辑FirstClass的属性。在

这可能吗?在


Tags: name编辑属性custompropertyjohnclasssteve
2条回答

因为您使用的是python3.6,所以您可以通过使用新的^{}方法来完成您的要求。来自__init_subclass__的文档:

This method is called whenever the containing class is subclassed. cls is then the new subclass. If defined as a normal instance method, this method is implicitly converted to a class method.

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及更低版本的方法,可以使用一些元类魔术:

^{pr2}$

@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,因为这已经是语言中的关键字了

相关问题 更多 >