class 函数中有没有办法 return class 本身的一个实例?

Is there a way in a class function to return an instance of the class itself?

我在 python 中有一个带有函数的 class,我需要该函数来显式 return 那个 class 的一个实例。我试过这个

class a(type):
    def __init__(self, n):
        self.n = n

    def foo() -> a:
        return a(self.n + 1)

但我得到一个错误 "a is not defined"。我应该怎么办?谢谢。

你问的有效:

class A:
    def __init__(self, n):
        self.n = n

    def foo(self):
        return A(self.n + 1)


a = A(1)
b = a.foo()

print(a.n, b.n)

尽管您的原始代码存在一些问题。

  • 类型提示 -> A 不起作用,因为 A 在该点未定义。
  • 您还需要将 self 传递给 foo 方法。
  • 如果您对 type 进行子类化并希望利用其功能,我建议您也通过调用 super().__init__() 来初始化它并传递所有必要的参数。您可以在任何时候这样做,但通常是在子类的 __init__() 方法中完成。

由于OP在成员函数中使用了注解。注释中也有一个 NameError。解决这个问题。尝试以下操作:

参考:

https://www.python.org/dev/peps/pep-0484/#id34

Annotating instance and class methods

In most cases the first argument of class and instance methods does not need to be annotated, and it is assumed to have the type of the containing class for instance methods, and a type object type corresponding to the containing class object for class methods. In addition, the first argument in an instance method can be annotated with a type variable. In this case the return type may use the same type variable, thus making that method a generic function.

from typing import TypeVar

T = TypeVar('T', bound='a')


class a:
    def __init__(self: T, n: int):
        self.n = n

    def foo(self: T) -> T:
        return a(self.n + 1)


print(a(1).foo().n)

结果:

2