Search notes:

Python: statement class

The class statement creates

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()
Github repository about-python, path: /statements/class/constructor.py

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()
Github repository about-python, path: /statements/class/calling-base-classes-constructor.py
See also the built-in function super().

Metaclass

A class definition consists of
These items are managed by a class's metaclass.
TODO: compare with __new__

See also

The class statement is just a «container» for a series of statements.
Nested classes
The class statement calls __build_class__ behind the scenes.
statements

Index