【发布时间】:2020-12-07 15:09:59
【问题描述】:
如何在静态方法中获取对类的引用?
我有以下代码:
class A:
def __init__(self, *args):
...
@staticmethod
def load_from_file(file):
args = load_args_from_file(file)
return A(*args)
class B(A):
...
b = B.load_from_file("file.txt")
但我想 B.load_from_file 返回 B 类型的对象,而不是 A。 我知道 load_from_file 是否不是我可以做的静态方法
def load_from_file(self, file):
args = load_args_from_file(file)
return type(self)__init__(*args)
【问题讨论】:
-
静态方法无法访问根据定义的类。你为什么不想要别的东西,比如类方法?
-
是的,谢谢,从未听说过类方法,这正是我需要的。
-
@JaraM 我建议您也搜索 factory method pattern(更通用的术语),特别是如果您想与
python以外的语言进行比较。 -
@Daweo:需要明确的是,该设计模式旨在弥补其他语言的空白;在 Python 中,坚持
classmethods。 -
@Daweo 仍然很高兴知道存在类似的东西 :)
标签: python static-methods