< 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.
%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__
class ComplexNumber:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = ComplexNumber(3.0, -4.5)
x.r, x.i
We can also set default values in the __init__ function
class ComplexNumber:
def __init__(self, realpart=0, imagpart=0):
self.r = realpart
self.i = imagpart
x = ComplexNumber()
x.r, x.i
Defining empty classes can sometimes be useful for datatype defs
class Employee:
pass
john = Employee() # Create an empty employee record
# Fill in the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
print(john.name)
print(john.salary)
print(john.dept)
Class and instance variables¶
class Horse:
is_hairy = True # class variable shared by all instances
def __init__(self, breed):
self.breed = breed # instance variable unique to each instance
h1 = Horse("Arabian")
h2 = Horse("Draft")
print(h1.breed)
print(h2.breed)
print(h1.is_hairy)
print(h2.is_hairy)
Use self.method_name to call a method from within the class that you are currently 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
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
horse_1 = Horse()
horse_2 = Horse(kicksOwners=True)
dog_1 = Dog()
dog_2 = Dog(likesToBark=True)
print(horse_1.hasHair)
print(horse_1.hasMammaryGlands)
print(horse_1.hasVertebrate)
print(horse_1.kicksOwners)
print(horse_1.makesSound)
print(horse_1.hasTail)
Multiple inheritance¶
class DerivedClassName(Base1, Base2, Base3): pass
Multiple inheritance works the same way as single inheritance except you interit multiple base classes.
class Base1:
pass
class Base2:
pass
class Base3:
pass
class DerivedClass(Base1, Base2, Base3):
pass
DerivedClass.__bases__
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.
# Define a parent class
class Parent:
def __init__(self):
self.value = 4
def get_value(self):
return self.value
# Child inherits the previously defined Parent class
class Child(Parent):
def get_value(self):
return self.value + 1
p = Parent()
c = Child()
p.get_value()
c.get_value()
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
# import sys
# print(sys.version)
# !jupyter --version
< Functions in Python | Contents | Permutations and Combinations in Python >