Is the following python code valid?
class Test: def __init__(self): self.number = 5 def returnTest(self): return Test()
Yes, a class can have a method that returns an instance of itself.
To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With