Here I have defined immutable class str. In new method I am changing the values of instances such as "hello" to uppercase. Why should we do it using new when we can define upper in init ?
class Upperstr(str):
def __new__(cls,value=""):
print(cls)
print(value)
return str.__new__(cls,value.upper())
# def __init__(self,m1):
# self.m1 = m1.upper()
u = Upperstr("hello")
print(u)
New is used to create class instances. What are the other uses of new method?
CodePudding user response:
New is used to create class instances. What are the other uses of new method?
You can use __new__
to implement singleton pattern (where pattern must be understand as thing described in Design Patterns: Elements of Reusable Object-Oriented Software), take look at example provided by geeksforgeeks.org of Classic Singleton
class SingletonClass(object):
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance = super(SingletonClass, cls).__new__(cls)
return cls.instance
singleton = SingletonClass()
new_singleton = SingletonClass()
print(singleton is new_singleton)
singleton.singl_variable = "Singleton Variable"
print(new_singleton.singl_variable)
CodePudding user response:
new is basically a standard Python method that is invoked before init when a class instance is created. For further information, see the python new manual: https://docs.python.org/3/reference/datamodel.html#object.__new__
There is not other direct usage of it.
Regarding the difference between Init/New: The constructor function in python is called new and init is the initializer function. According to the Python documentation, new is used to control the creation of a new instance, whereas init is used to handle its initialization.