Constructor
The name of a class's constructor is
__init__
#!/usr/bin/python
class ABC:
def __init__(self, x, y):
#
# The class's constructor.
# The first parameter is automatically aliased
# to the instance being constructed.
#
print('Constructor being executed')
self.x = x
self.y = y
def show(self):
print('x = {:d}, y = {:s}'.format(self.x, self.y))
#
# Initialize an instance of a class.
# Note: there is no 'new' statement, using
# the class name with following paranthesis
# is sufficient.
#
abc = ABC(42, 'foo')
abc.show()
Calling the constructor of a base class
Unlike in
C++, the constructor of a derived class does not call the constructor of the base class. If desired, it needs to be explicitly called.
class A:
def __init__(self, ident):
print(f" A's constructor, ident = {ident}")
self.ident = ident
def printIdent(self):
print(self.ident)
class B(A):
def __init__(self, ident):
# Call A's constructor:
print(" B's constructor")
A.__init__(self, ident)
class C(A):
def __init__(self, ident):
# Note: A's constructor is not called
print(" C's constructor")
print('Creating a B')
b = B(42)
print('Creating a C')
c = C(49)
b.printIdent()
# c.printIdent()
See also the built-in function
super()
.