Python Class Constructors
Python Class Constructors
1 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
.__init__()
.__new__()
class
SomeClass class
pass
SomeClass
2 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
.__call__()
.__new__()
.__init__()
.__init__() self
.__new__()
.__init__()
Point
.__new__() .__init__()
# point.py
class Point:
def __new__(cls, *args, **kwargs):
print("1. Create a new instance of Point.")
return super().__new__(cls)
Point class
.__new__() cls
self *args
**kwargs
.__new__()
.__init__() self
x y
.x .y
Point()
3 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
.__init__()
.x .y x y
.__repr__() Point
Point point.py
>>> point
Point(x=21, y=42)
Point()
point
.__new__() Point
.__init__()
.__init__()
Point
.__new__()
4 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
.__init__()
.__new__() B A
# ab_classes.py
class A:
def __init__(self, a_value):
print("Initialize the new instance of A.")
self.a_value = a_value
class B:
def __new__(cls, *args, **kwargs):
return A(42)
B.__new__() B.__init__()
ab_classes.py
>>> b = B(21)
Initialize the new instance of A.
>>> b.b_value
Traceback (most recent call last):
...
AttributeError: 'A' object has no attribute 'b_value'
>>> isinstance(b, B)
False
>>> isinstance(b, A)
True
>>> b.a_value
42
.__init__() .__new__()
.__init__()
.__init__()
.__init__()
.__init__()
5 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
.__init__()
Rectangle .width .height
.__init__() self
.__new__() .__init__()
.width .height width height
.__init__()
self .__init__()
.__init__()
.__init__() TypeError
.__init__()
Rectangle width height
6 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
.__init__() .__init__()
super()
>>> john.name
'John Doe'
>>> john.birth_date
'2001-02-07'
>>> john.position
'Python Developer'
.__init__() object
.__init__()
7 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
.__init__()
Greeter
# greet.py
class Greeter:
def __init__(self, name, formal=False):
self.name = name
self.formal = formal
def greet(self):
if self.formal:
print(f"Good morning, {self.name}!")
else:
print(f"Hello, {self.name}!")
formal False
.greet()
Greeter greet.py
informal_greeter name
formal .greet() informal_greeter
.__init__()
.__new__()
.__new__()
.__new__()
object
.__new__()
8 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
.__new__()
.__new__()
super().__new__()
class SomeClass:
def __new__(cls, *args, **kwargs):
instance = super().__new__(cls)
# Customize your instance here...
return instance
.__new__() .__new__()
cls
*args **kwargs
.__new__() *args **kwargs
.__new__() .__new__()
.__new__() super()
object.__new__() .__new__()
object
object.__new__()
object.__new__() TypeError
>>> SomeClass(42)
Traceback (most recent call last):
...
TypeError: object.__new__() takes exactly one argument (the type to instantiate)
object.__new__() .__init__()
9 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
.__new__() SomeClass
.__new__()
.__new__()
Distance float
.__init__()
float.__new__()
object.__new__()
.__new__() .__init__()
10 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
>>> dir(in_miles)
['__abs__', '__add__', ..., 'real', 'unit']
.__new__()
cls super().__new__() float.__new__()
value .unit
Distance
Distance(10, "km") + Distance(20, "miles")
Distance
Distance .unit
dir()
float
.__new__()
Pet .__new__()
11 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
# pets.py
class Pet:
def __new__(cls):
other = choice([Dog, Cat, Python])
instance = super().__new__(other)
print(f"I'm a {type(instance).__name__}!")
return instance
def __init__(self):
print("Never runs!")
class Dog:
def communicate(self):
print("woof! woof!")
class Cat:
def communicate(self):
print("meow! meow!")
class Python:
def communicate(self):
print("hiss! hiss!")
Pet .__new__()
Pet
Pet
.__new__() .__new__()
.__new__()
12 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
Singleton .__new__()
.__new__()
Singleton .__init__()
.__init__() Singleton()
if Singleton cls._instance
collections.namedtuple
.__new__()
collections.namedtuple() namedtuple() tuple
named_tuple_factory()
.__new__() NamedTuple
13 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
# named_tuple.py
class NamedTuple(tuple):
__slots__ = ()
def __repr__(self):
return f"""{type_name}({", ".join(repr(arg) for arg in self)})"""
return NamedTuple
itemgetter() operators
named_tuple_factory() type_name
*fields
NamedTuple tuple
.__slots__
.__dict__
TypeError
.__name__ type_name
for itemgetter()
index setattr() enumerate()
index
super().__new__()
.__repr__()
NamedTuple
named_tuple_factory() named_tuple.py
14 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
>>> point.x = 84
Traceback (most recent call last):
...
AttributeError: can't set attribute
>>> dir(point)
['__add__', '__class__', ..., 'count', 'index', 'x', 'y']
Point named_tuple_factory()
Point .x .y
AttributeError
dir() point
.__new__() .__init__()
.__new__() .__init__()
.__init__()
.__new__()
15 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
16 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
17 of 18 4/1/2022, 9:18 PM
Python Class Constructors: Control Your Object Instantiation – Real Python https://realpython.com/python-class-constructor/#:~:text=Class%20constructors%20are%20a%20fu...
⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅
⋅ ⋅ ⋅ ⋅ ⋅
18 of 18 4/1/2022, 9:18 PM