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.
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.
There are many more special methods, as described in the official documentation. We will not go there.
In [1]:
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)
In [2]:
A.__doc__
Out[2]:
In [3]:
help(A)
In [4]:
A.report.__doc__
Out[4]:
In [5]:
class X:
"""Empty class."""
In [6]:
x = X()
print(x)
In [7]:
a0 = A('a')
In [8]:
print(a0)
In [9]:
a1 = A(x = 3.14)
In [10]:
print(a1)
In [11]:
a0.x, a1.x
Out[11]:
In [12]:
a0.report(), a1.report()
Out[12]:
In [13]:
class B(A):
"""Derived class inherits from A."""
def report(self):
"""Overwrite report() method of A."""
return self.x
In [14]:
B.__doc__
Out[14]:
In [15]:
b0 = B(3 + 4j)
In [16]:
b1 = B(x = a1)
In [17]:
b0.x
Out[17]:
In [18]:
b1.x
Out[18]:
In [19]:
b1.report()
Out[19]:
In [20]:
b1.x.report()
Out[20]: