[英]Python using child class's class attribute as default parameter without overriding method
While initializing a class, the default arg for a parameter is a constant class attribute.在初始化 class 时,参数的默认 arg 是常量 class 属性。
class SomeClass:
"""Some class."""
DEFAULT_VAL = 0
def __init__(self, some_param: int = DEFAULT_VAL):
print(f"default = {self.DEFAULT_VAL} and some_param = {some_param}.")
some_class = SomeClass()
Prints: default = 0 and some_param = 0.
打印: default = 0 and some_param = 0.
When I subclass the class, and override the constant class attribute, it doesn't use it as the default parameter.当我将 class 子类化并覆盖常量 class 属性时,它不会将其用作默认参数。
class SomeChildClass(SomeClass):
"""Some child class."""
DEFAULT_VAL = 1
some_child_class = SomeChildClass()
Prints: default = 1 and some_param = 0.
打印: default = 1 and some_param = 0.
Is there some way I can make this work, without explicitly overriding __init__
in the child class?有什么方法可以让我完成这项工作,而无需在子 class 中显式覆盖__init__
?
Research研究
How to call parent class init with default values from child class? 如何使用子 class 的默认值调用父 class init?
Question is very similar, yet they override __init__
.问题非常相似,但它们覆盖了__init__
。
Reinitialize parent class attributes during child class definition 在子 class 定义期间重新初始化父 class 属性
Presents a possible solution using a metaclass
to specify DEFAULT_VAL
via __new__
.提供一个可能的解决方案,使用metaclass
通过__new__
指定DEFAULT_VAL
。 This solution adds verbosity to SomeClass
, which is not half bad.这个解决方案增加了SomeClass
的冗长,这还不错。 I am wondering if it can be done even simpler though.我想知道它是否可以做得更简单。
Overriding class variables in python 覆盖 python 中的 class 变量
In this answer , it informs me the problem is that DEFAULT_VAL
is evaluated when the function __init__
is defined.在这个答案中,它告诉我问题是在定义 function __init__
时评估DEFAULT_VAL
。 However, I am not quite sure if using a classmethod
is applicable in my use case.但是,我不太确定使用classmethod
是否适用于我的用例。
The problem here is that default values take objects, not variables/attributes .这里的问题是默认值采用对象,而不是变量/属性。 The object is evaluated once when the function is defined. object 在定义 function 时评估一次。 The generic way to solve this in any function is to do something like:在任何 function中解决此问题的通用方法是执行以下操作:
class SomeClass:
"""Some class."""
DEFAULT_VAL = 0
def __init__(self, some_param: int = None):
if some_param is None:
some_param = self.DEFAULT_VAL
print(f"default = {self.DEFAULT_VAL} and some_param = {some_param}.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.