Basic Python

__new__, __init__

Naranjito 2022. 7. 13. 11:09
  • __new__

- A static method of the object class.

- When you create a new object by calling the class, the __new__() method to create the object first and then calls the __init__() method to initialize the object’s attributes.

- It receives the class as itself.

- Must create object, return object. 

 

  • __init__

- It customizing/initiating instances which created with __new__ to be used as desired by the user. 

- For example, self.x=x, self.y=y

class Point():
    def __new__(cls, *args, **kwargs):
        print('from now')
        print(cls)
        print(args)
        print(kwargs)
        obj=super().__new__(cls)
        return obj
    def __init__(self, x=0, y=0):
        print('from init')
        self.x=x
        self.y=y

class RectPoint(Point):
    MAX_Inst=2
    Inst_created=0
    def __new__(cls, *args, **kwargs):
        if (cls.Inst_created>=cls.MAX_Inst):
            raise ValueError('cannot create more object')
        cls.Inst_created+=1
        return super().__new__(cls)
    
p1=RectPoint(0,0)
p2=RectPoint(1,0)
p3=RectPoint(1,1)

>>>

from now
<class '__main__.RectPoint'>
()
{}
from init

from now
<class '__main__.RectPoint'>
()
{}
from init

Traceback (most recent call last):
  
  ...
  
    raise ValueError('cannot create more object')
ValueError: cannot create more object

 

  • __call__

When implemented inside a class, gives its instances (objects) the ability to behave like a function.

class Calc:
    def __call__(self, n1, n2):
        self.n1=n1
        self.n2=n2
        return print(self.n1+self.n2)  
s=Calc()
s(7,8)

>>>
15

 

 

TIPS

  • __new__ is called before __init__.
  • __new__ returns a instance of class.
  • __init__ receives the instances of the class returned by __new__.
  • Use __init__ to initilize value.

 

reference

- https://santoshk.dev/posts/2022/__init__-vs-__new__-and-when-to-use-them/

- https://www.pythontutorial.net/python-oop/python-__new__/#:~:text=new__()%20method.-,Summary,to%20initialize%20the%20object's%20attributes. 

- https://weeklyit.code.blog/2019/12/24/2019-12%EC%9B%94-3%EC%A3%BC-python%EC%9D%98-__init__%EA%B3%BC-__new__/

- https://dev.to/delta456/python-init-is-not-a-constructor-12on

'Basic Python' 카테고리의 다른 글

lambda  (0) 2022.11.29
vars  (0) 2022.08.25
Underscore(_)  (0) 2022.07.05
instancemethod, classmethod, staticmethod  (0) 2022.07.01
TypeError : Can't instantiate abstract class with abstract method  (0) 2022.06.29