Classes in Python
1 How are classes different from functions?
Classes create a new object type that provides both data and functionality while functions only provide the latter.
Classes can be instantiated to create a new object (an instance).
Classes create a new namespace.
2 Defining a class
A simple class:
class Accumulator:
# attribute variable
total = 0
# attribute function requires self (Accumulator in this case) as the first argument
# Accumulator.add() is a function object
def add(self, x):
self.total += x # access the total attribute
def print(self):
print(self.total)
accum = Accumulator()
# accum.add() is a method object
accum.add(1) # the first self argument is missing
accum.add(2)
accum.print()
# what about this?
Accumulator.add(1)
Accumulator.add(2)
Accumulator.print()
3 Class with arguments
Define a class with arguments.
class Accumulator2:
def __init__(self, start): # automatically invoked when an instance is created
self.total = start
def add(self, x):
self.total += x
def print(self):
print(self.total)
accum = Accumulator2(3)
accum.add(1)
accum.add(2)
accum.print()
4 Class variables
All objects instantiated from the same class share class variables.
class Dog:
kind = 'canine' # class variable shared by instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
fido = Dog('Fido')
print(fido.kind, fido.name)
Dog.kind = 'feline'
buddy = Dog('Buddy') # inherits feline
print(buddy.kind, buddy.name)
Dog.kind = 'bovine'
print(buddy.kind, buddy.name) # kind from the class
buddy.kind = 'canine' # creates its own kind attribute
Dog.kind = 'bovine'
print(buddy.kind, buddy.name) # no more from the class
print(Dog.kind)
print(Dog.name) # Oops! # classes don't have instance variables
5 Derived classes
We can derive a class from a base class.
class Mammal:
hair = True
def __init__(self, name):
self.name = name
def walk(self):
print('{name} walks'.format(name=self.name))
class Dog(Mammal):
def bark(self):
print('{name} barks'.format(name=self.name))
dog = Mammal('A dog')
print(dog.hair)
dog.walk()
buddy = Dog('Buddy')
buddy.walk()
buddy.bark()
6 Defining a regular function using a class
Recall the __call__
attribute? We can do the same
class Accumulator:
def __init__(self):
self.sum = 0
def __call__(self, x):
self.sum += x
def print(self):
print(self.sum)
accum = Accumulator()
accum(1) # just like a regular function
accum(2)
accum.__call__(3) # alternative way
accum.print()
7 What about class pointers?
Classes also have their pointers.
class Class:
def __init__(self, val):
self.x = val
def print_x(self):
print(self.x)
def Return(c):
return c
a = Return(Class)(10) # indirect instantiation
a.print_x()
b = Class(20)
b.print_x()
8 Exercises
8.1 Exercise: TupleLister
Write a class that takes a tuple when creating an instance and provides a print method that lists all elements in the tuple one per line.
class TupleLister:
# your code here
tupls = TupleLister(('apple', 'orange', 'pear'))
tupls.print()
# apple
# orange
# pear
8.2 Exercise: FactSum
Write a class that takes a positive integer and provides two methods for factorial (fact
) and summation (sum
).
class FactSum:
# your code here
factsum = FactSum(5)
print(factsum.fact())
print(factsum.sum())
# 120
# 15
8.3 Exercise: SportsCar
Write a Car
class with the name
, has_engine
, and max_passengers
variables and the start
function.
Write a SportsCar
class derived from the Car
class that provides an additional has_turbo
variable and overrides the start
function.
class Car:
# your code here
class SportsCar:
# your code here
boring_car = Car('My Car')
print(boring_car.name) # My Car
print(boring_car.has_engine) # True
print(boring_car.max_passengers) # 5
boring_car.start() # vroom...
dream_car = SportsCar('Dream Car')
print(dream_car.name) # Dream Car
print(dream_car.has_engine) # True
print(dream_car.has_turbo) # True
print(dream_car.max_passengers) # 2
dream_car.start() # Vrooooom!!!