猿问

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

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


我有以下代码:


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)


郎朗坤
浏览 102回答 1
1回答

慕容708150

这就是classmethods 的用途;它们的相似之处staticmethod在于它们不依赖于实例信息,但它们通过将其作为第一个参数隐式提供来提供有关它被调用的类的信息。只需将您的备用构造函数更改为:@classmethod                          # class, not static methoddef 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能够正确地启用继承。
随时随地看视频慕课网APP

相关分类

Python
我要回答