【问题标题】:Python how to get reference to class in static method [duplicate]Python如何在静态方法中获取对类的引用[重复]
【发布时间】: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


【解决方案1】:

这就是classmethods 的作用;它们就像staticmethod,因为它们不依赖于实例信息,但它们确实提供了关于它被调用的类的信息,隐含地提供它作为第一个论点。只需将您的备用构造函数更改为:

@classmethod                          # class, not static method
def load_from_file(cls, file):        # Receives reference to class it was invoked on
    args = load_args_from_file(file)
    return cls(*args)                 # Use reference to class to construct the result

当B.load_from_file 被调用时,cls 将是B,即使该方法是在A 上定义的,确保您构造了正确的类。

一般来说,每当您发现自己编写这样的替代构造函数时,您总是需要classmethod 来正确启用继承。

【讨论】:

    猜你喜欢
    • 2016-08-04
    • 2016-06-05
    • 1970-01-01
    • 2017-07-05
    • 2020-04-15
    • 2014-06-08
    • 2012-01-28
    相关资源
    最近更新 更多