Classes

As you probably know, Python is an object-oriented language, and so it has very strong support for objects. In fact, everything in Python is an object. We will mostly use an imperative or functional rather than object-oriented programming style in this course.

Here is the bare minimum about Python objects.

Defining a new class

We define a class A with two ‘special’ double underscore methods and one normal method. This class will have an attribute x that is specified at the time of creating new instances of the class.

  • The init method initializes properties of any new instance of A
  • The repr method provides an accurate string representation of A. For example, if we print an instance of A, the repr method will be used. If you don’t specify a repr (or str) special method, the default name when printing only gives the address in memory.

There are many more special methods, as described in the official documentation. We will not go there.

class A:
    """Base class."""

    def __init__(self, x):
        self.x = x

    def __repr__(self):
        return '%s(%a)' % (self.__class__.__name__, self.x)

    def report(self):
        """Report type of contained value."""

        return 'My value is of type %s' % type(self.x)

Docstrings

A.__doc__
'Base class.'
help(A)
Help on class A in module __main__:

class A(builtins.object)
 |  Base class.
 |
 |  Methods defined here:
 |
 |  __init__(self, x)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __repr__(self)
 |      Return repr(self).
 |
 |  report(self)
 |      Report type of contained value.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)
A.report.__doc__
'Report type of contained value.'

Creating an instance of a class

Example of a class without repr.

class X:
    """Empty class."""
x = X()
print(x)
<__main__.X object at 0x106e7fcc0>

Create new instances of the class A

a0 = A('a')
print(a0)
A('a')
a1 = A(x = 3.14)
print(a1)
A(3.14)

Attribute access

a0.x, a1.x
('a', 3.14)

Method access

a0.report(), a1.report()
("My value is of type <class 'str'>", "My value is of type <class 'float'>")

Class inheritance

class B(A):
    """Derived class inherits from A."""

    def report(self):
        """Overwrite report() method of A."""
        return self.x
B.__doc__
'Derived class inherits from A.'

Create new instances of class B

b0 = B(3 + 4j)
b1 = B(x = a1)

Attribute access

b0.x
(3+4j)
b1.x
A(3.14)

Method access

b1.report()
A(3.14)

Nested attribute access

b1.x.report()
"My value is of type <class 'float'>"