Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a python class return a new instance of its class?

Tags:

Is the following python code valid?

class Test:   def __init__(self):     self.number = 5    def returnTest(self):     return Test() 
like image 872
cytinus Avatar asked May 30 '12 06:05

cytinus


People also ask

Can a class return an instance of itself?

Yes, a class can have a method that returns an instance of itself.

How do I create a new instance of a class in Python?

To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.

What is __ new __ in Python?

The __new__() is a static method of the object class. When you create a new object by calling the class, Python calls the __new__() method to create the object first and then calls the __init__() method to initialize the object's attributes.

What does Python call when a new instance of a class is created?

The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class.


1 Answers

Yes it is valid. The class is defined by the time you create an object and call the returnTest method.

In [2]: x = Test()  In [3]: y = x.returnTest()  In [4]: y Out[4]: <__main__.Test instance at 0x1e36ef0>  In [5]:  

However, in cases where a method acts like a factory, you might want to consider using the classmethod decorator. When inheritance and other annoyances come in the way, this can help.

like image 53
Noufal Ibrahim Avatar answered Oct 12 '22 15:10

Noufal Ibrahim