当我无法使用 self - Python 时如何获取 class

How to get class when I can't use self - Python

我有一个奇怪的问题。我有以下代码:

class A:
    def f():
        return __class__()

class B(A):
    pass
a = A.f()
b = B.f()
print(a, b)

输出是这样的:

<__main__.A object at 0x01AF2630> <__main__.A object at 0x01B09B70>

那么我怎样才能得到 B 而不是第二个 A

magic __class__ closure 是为 方法上下文设置的 并且仅供 super() 使用。

对于您想使用 self.__class__ 的方法:

return self.__class__()

或更好,使用 type(self):

return type(self)()

如果您希望能够在 class 上调用该方法,则使用 classmethod decorator 传递对 class 对象的引用,而不是保持未绑定状态:

@classmethod
def f(cls):
    return cls()

classmethods 总是绑定到他们被调用的 class,所以对于 A.f() 那将是 A,对于 B.f() 你上交B.