- __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
|
reference
- https://santoshk.dev/posts/2022/__init__-vs-__new__-and-when-to-use-them/
- 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 |