在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
的属性。
这可能吗?
答案 0 :(得分:4)
由于您使用的是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)
答案 1 :(得分:1)
@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
,因为它已经是语言中的关键字