为了账号安全,请及时绑定邮箱和手机立即绑定

Python如何在静态方法中获取对类的引用

Python如何在静态方法中获取对类的引用

郎朗坤 2023-06-06 10:29:09
如何在静态方法中获取对类的引用?我有以下代码: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)
查看完整描述

1 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

这就是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能够正确地启用继承。


查看完整回答
反对 回复 2023-06-06
  • 1 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信