The content for this site available on GitHub. If you want to launch the notebooks interactively click on the binder stamp below. Binder

< Functions in Python | Contents | Permutations and Combinations in Python >

Classes in Python

Purpose: To help you get comfortable with the topics outlined below.

Recomended Usage

  • Run each of the cells (Shift+Enter) and edit them as necessary to solidify your understanding
  • Do any of the exercises that are relevant to helping you understand the material

Topics Covered

  • Basic Classes
  • Inheritance

Workbook Setup

The following magics will reload all modules before executing a new line and help make sure you follow PEP8 code style.

In [1]:
%load_ext autoreload
%autoreload 2

%load_ext pycodestyle_magic
%pycodestyle_on

Basic Classes

class ClassName:
    pass

Classes with initial state

We can initialize classes with an initial state using __init__

In [2]:
class ComplexNumber:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
In [3]:
x = ComplexNumber(3.0, -4.5)
x.r, x.i
Out[3]:
(3.0, -4.5)

We can also set default values in the __init__ function

In [4]:
class ComplexNumber:
    def __init__(self, realpart=0, imagpart=0):
        self.r = realpart
        self.i = imagpart
In [5]:
x = ComplexNumber()
x.r, x.i
Out[5]:
(0, 0)

Defining empty classes can sometimes be useful for datatype defs

In [2]:
class Employee:
    pass
In [3]:
john = Employee()  # Create an empty employee record
In [4]:
# Fill in the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
In [10]:
print(john.name)
print(john.salary)
print(john.dept)
John Doe
1000
computer lab

Class and instance variables

In [15]:
class Horse:

    is_hairy = True  # class variable shared by all instances

    def __init__(self, breed):
        self.breed = breed    # instance variable unique to each instance
In [21]:
h1 = Horse("Arabian")
h2 = Horse("Draft")
In [23]:
print(h1.breed)
print(h2.breed)
Arabian
Draft
In [24]:
print(h1.is_hairy)
print(h2.is_hairy)
True
True

Use self.method_name to call a method from within the class that you are currently in.

In [ ]:
class Bag:
    def __init__(self):
        self.data = []

    def add(self, x):
        self.data.append(x)

    def addtwice(self, x):
        self.add(x)
        self.add(x)

Inheritance

Single inheritance

The process by which one class takes on the attributes and methods of another.

class DerivedClassName(BaseClass):
    pass
In [14]:
class Mammal:
    hasVertebrate = True
    hasMammaryGlands = True
    hasHair = True    

class Horse(Mammal):
    makesSound = "neigh"
    hasTail = True
    
    def __init__(self, kicksOwners=False):
        self.kicksOwners = kicksOwners
    
class Dog(Mammal):
    makesSound = "bark"
    hasTail = True
    
    def __init__(self, likesToBark=False):
        self.likesToBark = likesToBark
In [16]:
horse_1 = Horse()
horse_2 = Horse(kicksOwners=True)

dog_1 = Dog()
dog_2 = Dog(likesToBark=True)
In [20]:
print(horse_1.hasHair)
print(horse_1.hasMammaryGlands)
print(horse_1.hasVertebrate)

print(horse_1.kicksOwners)
print(horse_1.makesSound)
print(horse_1.hasTail)
True
True
True
False
neigh
True

Multiple inheritance

class DerivedClassName(Base1, Base2, Base3):
    pass

Multiple inheritance works the same way as single inheritance except you interit multiple base classes.

In [36]:
class Base1:
    pass


class Base2:
    pass


class Base3:
    pass
In [37]:
class DerivedClass(Base1, Base2, Base3):
    pass
In [40]:
DerivedClass.__bases__
Out[40]:
(__main__.Base1, __main__.Base2, __main__.Base3)

Overriding the functionality of a parent class

If you want to inherit a base class but want to change the way it handles a particular function you can override it like this.

In [15]:
# Define a parent class
class Parent:
    def __init__(self):
        self.value = 4
    
    def get_value(self):
        return self.value
In [14]:
# Child inherits the previously defined Parent class
class Child(Parent):
    
    def get_value(self):
        return self.value + 1
In [47]:
p = Parent()
c = Child()
In [48]:
p.get_value()
Out[48]:
4
In [45]:
c.get_value()
Out[45]:
5

Troubleshooting Tips

If you run into issues running any of the code in this notebook, check your version of Python and Jupyter against mine below

import sys
print(sys.version)
3.7.6 (default, Dec 31 2019, 17:12:14) 
[Clang 11.0.0 (clang-1100.0.33.16)]
!jupyter --version
jupyter core     : 4.6.1
jupyter-notebook : 6.0.2
qtconsole        : not installed
ipython          : 7.9.0
ipykernel        : 5.1.3
jupyter client   : 5.3.4
jupyter lab      : 1.2.3
nbconvert        : 5.6.1
ipywidgets       : not installed
nbformat         : 4.4.0
traitlets        : 4.3.3
In [7]:
# import sys
# print(sys.version)
In [6]:
# !jupyter --version


< Functions in Python | Contents | Permutations and Combinations in Python >