pythonclassreturninstance

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


I have a class in python with a function and I need that function to explicitly return an instance of that class. I tried this

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

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

but I get an error "a is not defined". What should I do? Thanks.


Solution

  • Since OP used annotation in member function. There is a NameError in the annotation also. To fix that. Try following:

    Reference:

    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)
    

    Result:

    2