Inheritance and Polymorphism
Published by Brayan K
Create extensible class hierarchies, reuse behavior safely, and design APIs that stay flexible as your codebase grows.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Error families are classes built on classes
Exception Handling showed errors in families: except LookupError also catches a KeyError, because a KeyError is a kind of LookupError. Each family is a class built on another class:
print(issubclass(KeyError, LookupError))
print(KeyError.__bases__)
print(LookupError.__bases__)
# ✅ Expected output:
# True
# (<class 'LookupError'>,)
# (<class 'Exception'>,)__bases__ lists the classes a class is built on. Building one class on another is called inheritance: the new class, the child, gets the methods of the class it's built on, its parent, and adds or changes what it needs. Parents are also called base classes or superclasses, and children subclasses.
The class in brackets is the parent
Here is the Account from Object-Oriented Programming, and a savings account built on it. The parent's name goes in brackets after the child's:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be more than 0")
self.balance += amount
class SavingsAccount(Account):
def add_interest(self, rate):
self.deposit(self.balance * rate // 100)
savings = SavingsAccount("Ada")
savings.deposit(200)
savings.add_interest(5)
print(savings.owner, savings.balance)
print(issubclass(SavingsAccount, Account))
# ✅ Expected output:
# Ada 210
# True- SavingsAccount has no __init__ and no deposit() of its own. For SavingsAccount("Ada"), Python looks for __init__ on SavingsAccount, doesn't find one, and runs Account's; savings.deposit(200) works the same way.
- Object-Oriented Programming showed Python looking up a name on the object first, then on its class. Next come the classes that class is built on, in turn.
- add_interest() is new, so only savings accounts have it. It calls self.deposit(), which it got from Account: 200 × 5 // 100 adds 10.
The child gets the parent's checks as well as its work, but nothing goes the other way: a plain Account doesn't get the child's methods.
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be more than 0")
self.balance += amount
class SavingsAccount(Account):
def add_interest(self, rate):
self.deposit(self.balance * rate // 100)
savings = SavingsAccount("Ada")
try:
savings.deposit(-50)
except ValueError as e:
print("Refused:", e)
current = Account("Ben")
current.add_interest(5)
# ✅ Expected output:
# Refused: deposit must be more than 0
# ✅ Expected error:
# AttributeError: 'Account' object has no attribute 'add_interest'Every class is built on something. Account's brackets are empty, yet it has a parent too:
class Account:
pass
class SavingsAccount(Account):
pass
savings = SavingsAccount()
print(type(savings))
print(SavingsAccount.__bases__)
print(Account.__bases__)
# ✅ Expected output:
# <class '__main__.SavingsAccount'>
# (<class '__main__.Account'>,)
# (<class 'object'>,)A class with no brackets is built on object, the class every other class is built on. That's why older code's class Account(object): means the same as class Account:.
A child's __init__ replaces its parent's
Now give each savings account its own interest rate, passed when it's made. Without an __init__ of its own, SavingsAccount still uses Account's, which has no room for a rate:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
class SavingsAccount(Account):
def add_interest(self, rate):
self.balance += self.balance * rate // 100
savings = SavingsAccount("Ada", 5)
# ✅ Expected error:
# TypeError: Account.__init__() takes 2 positional arguments but 3 were givenThe message names Account.__init__(), though the code called SavingsAccount: Account's __init__ is the one that ran, and it takes the object and an owner, two arguments, not three. So the child needs an __init__ of its own. Python finds that one first and stops looking, so Account's never runs:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be more than 0")
self.balance += amount
class SavingsAccount(Account):
def __init__(self, owner, rate):
self.rate = rate
def add_interest(self):
self.deposit(self.balance * self.rate // 100)
savings = SavingsAccount("Ada", 5)
print(vars(savings))
savings.deposit(200)
# ✅ Expected output:
# {'rate': 5}
# ✅ Expected error:
# AttributeError: 'SavingsAccount' object has no attribute 'balance'vars() shows the object holds only its rate: no owner and no balance, because nothing set them. The error only comes later, inside Account's deposit(), at self.balance += amount: a correct line in the parent, with the mistake in the child. As Object-Oriented Programming put it, an attribute exists only once something assigns it.
super().__init__(owner) runs the parent's __init__ on the same object, so it belongs at the top of the child's:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be more than 0")
self.balance += amount
class SavingsAccount(Account):
def __init__(self, owner, rate):
super().__init__(owner)
self.rate = rate
def add_interest(self):
self.deposit(self.balance * self.rate // 100)
savings = SavingsAccount("Ada", 5)
print(vars(savings))
savings.deposit(200)
savings.add_interest()
print(savings.balance)
# ✅ Expected output:
# {'owner': 'Ada', 'balance': 0, 'rate': 5}
# 210Inside a method, super() gives you the parent's version of a method for the same object. With one parent, super().__init__(owner) does what Account.__init__(self, owner) does, the way Object-Oriented Programming showed rex.bark() meaning Dog.bark(rex): super() passes self for you. Pass it again, and the parent gets one argument too many:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
class SavingsAccount(Account):
def __init__(self, owner, rate):
super().__init__(self, owner)
self.rate = rate
savings = SavingsAccount("Ada", 5)
# ✅ Expected error:
# TypeError: Account.__init__() takes 2 positional arguments but 3 were givenIt's the same message as before, for a different reason: Account's __init__ got the object twice and the owner. Two other ways to get that line wrong fail straight away as well: Account.__init__(owner), with no object, stops with TypeError: Account.__init__() missing 1 required positional argument: 'owner', and super.__init__(owner), without the brackets after super, with the stranger TypeError: descriptor '__init__' requires a 'super' object but received a 'str'.
Where the call goes matters when the child sets an attribute the parent sets too:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
class GiftAccount(Account):
def __init__(self, owner, gift):
self.balance = gift
super().__init__(owner)
acct = GiftAccount("Ada", 20)
print(acct.balance)
# ✅ Expected output:
# 0Account's __init__ ran second and set the balance back to 0. Call super().__init__() first, then set what the child adds or changes: with the gift line moved below it, the same program prints 20.
Overriding replaces a method; super() adds to it
A method in the child with the same name as one in the parent overrides it: for the child's objects, Python finds the child's version first and never reaches the parent's. This account is meant to count its deposits:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be more than 0")
self.balance += amount
class CountingAccount(Account):
def __init__(self, owner):
super().__init__(owner)
self.deposit_count = 0
def deposit(self, amount):
self.deposit_count += 1
acct = CountingAccount("Ada")
acct.deposit(50)
acct.deposit(-5)
print(acct.deposit_count, acct.balance)
# ✅ Expected output:
# 2 0Both deposits were counted, the money never arrived, and the parent's check never ran, so the deposit of -5 counted too. To add to the parent's method rather than replace it, call it with super():
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be more than 0")
self.balance += amount
class CountingAccount(Account):
def __init__(self, owner):
super().__init__(owner)
self.deposit_count = 0
def deposit(self, amount):
super().deposit(amount)
self.deposit_count += 1
acct = CountingAccount("Ada")
acct.deposit(50)
acct.deposit(25)
try:
acct.deposit(-5)
except ValueError as e:
print("Refused:", e)
print(acct.deposit_count, acct.balance)
# ✅ Expected output:
# Refused: deposit must be more than 0
# 2 75super().deposit(amount) runs Account's deposit() for this account, check and all. The refused deposit raised its ValueError before the count line, so it wasn't counted. Calling self.deposit() there instead is a common slip: self.deposit is the child's own method, so it calls itself, again and again, until Python stops it about a thousand calls deep:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
self.balance += amount
class CountingAccount(Account):
def __init__(self, owner):
super().__init__(owner)
self.deposit_count = 0
def deposit(self, amount):
self.deposit(amount)
self.deposit_count += 1
acct = CountingAccount("Ada")
acct.deposit(50)
# ✅ Expected error:
# RecursionError: maximum recursion depth exceededAn override that builds on its parent's result must still return it:
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return f"{self.name} is an animal"
class Dog(Animal):
def describe(self):
super().describe() + " that barks"
print(Animal("Tom").describe())
print(Dog("Rex").describe())
# ✅ Expected output:
# Tom is an animal
# NoneDog's describe() builds the text and drops it, and a function that ends without return gives None. With return in front, it prints Rex is an animal that barks. A misspelt override is quieter still: name the child's method descibe, and nothing fails at all. The child simply has an extra method, and describe() runs the parent's, printing Rex is an animal.
A parent's method calls the child's version
When a parent's method calls self.area(), self is whatever object it was called on, so the lookup starts at that object's class: a child's version wins even inside the parent's code. One describe() serves every shape:
class Shape:
def area(self):
raise NotImplementedError("each shape must define area()")
def describe(self):
return f"{type(self).__name__} with area {self.area()}"
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
for shape in [Rectangle(3, 4), Square(5)]:
print(shape.describe())
# ✅ Expected output:
# Rectangle with area 12
# Square with area 25This is polymorphism, "many forms": the same call, shape.describe(), does the right thing for each kind of object. Shape's own area() raises NotImplementedError, a built-in error meant for exactly this: a method each child must write. A child that forgets it can still be made; the error waits for the call:
class Shape:
def area(self):
raise NotImplementedError("each shape must define area()")
def describe(self):
return f"{type(self).__name__} with area {self.area()}"
class Blob(Shape):
pass
blob = Blob()
print("Made a", type(blob).__name__)
print(blob.describe())
# ✅ Expected output:
# Made a Blob
# ✅ Expected error:
# NotImplementedError: each shape must define area()Abstract Base Classes (abc) shows how to refuse to make a Blob at all. Class attributes are looked up the same way as methods, so a child can change a parent's setting with one line:
class Account:
fee = 2
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount + self.fee
class StudentAccount(Account):
fee = 0
for acct in [Account("Ada"), StudentAccount("Ben")]:
acct.deposit(100)
acct.withdraw(10)
print(type(acct).__name__, acct.owner, acct.balance)
# ✅ Expected output:
# Account Ada 88
# StudentAccount Ben 90withdraw() is written once, in Account. Inside it, self.fee finds 0 on StudentAccount before it ever reaches Account's 2.
isinstance() counts children; type() doesn't
isinstance(obj, SomeClass) is True when the object's class is SomeClass or is built on it. Comparing type(obj) only matches the object's own class:
class Shape:
pass
class Square(Shape):
def __init__(self, side):
self.side = side
sq = Square(5)
print(type(sq) == Shape)
print(isinstance(sq, Shape))
print(isinstance(sq, Square), type(sq) == Square)
print(isinstance(sq, (int, float)))
# ✅ Expected output:
# False
# True
# True True
# FalseA tuple of classes asks "any of these?". The second argument must be a class, or a tuple of them: the string "Shape" stops with TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union. The rule is the one except uses, which is how except LookupError catches a KeyError:
prices = {"tea": 3}
try:
prices["coffee"]
except LookupError as e:
print(isinstance(e, LookupError), isinstance(e, KeyError))
print(type(e) == LookupError, type(e).__name__)
# ✅ Expected output:
# True True
# False KeyErrorisinstance() is handy for checking what you were given. Using it to choose what to do for each class is a habit worth spotting, though:
class Square:
def __init__(self, side):
self.side = side
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
class Circle:
def __init__(self, radius):
self.radius = radius
def area(shape):
if isinstance(shape, Square):
return shape.side ** 2
elif isinstance(shape, Rectangle):
return shape.width * shape.height
for shape in [Square(3), Rectangle(2, 5), Circle(1)]:
print(area(shape))
# ✅ Expected output:
# 9
# 10
# Nonearea() doesn't know Circle, and says nothing: it returns None. Every new shape means editing area(), and forgetting one fails silently. Giving each class its own area(), as Shape's children did, keeps the knowledge with the class, and a class without one fails loudly.
Polymorphism without a parent: duck typing
Python doesn't check an object's class before calling a method. It looks for the method when the call runs, so any object that has it will do, whatever it's built on: "if it walks like a duck and quacks like a duck, it's a duck". These two classes share no parent:
class Square:
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Field:
def __init__(self, width, length):
self.width = width
self.length = length
def area(self):
return self.width * self.length
def total_area(things):
return sum(thing.area() for thing in things)
print(total_area([Square(2), Square(3), Field(10, 20)]))
print(total_area([Square(2), "square"]))
# ✅ Expected output:
# 213
# ✅ Expected error:
# AttributeError: 'str' object has no attribute 'area'total_area() works for squares and fields alike, and fails only when it meets something without area(), at the moment it calls it. You have been using this since your first lessons: len(), + and max() each work on several types, and print() asks each object for its own __str__.
print(len("Ada"), len([3, 1, 2]), len({"a": 1}))
print("ab" + "cd", [1] + [2], 1 + 2)
print(max("cab"), max([3, 1, 2]))
# ✅ Expected output:
# 3 3 1
# abcd [1, 2] 3
# c 3When a list may hold things without the method, look the method up inside try and catch the AttributeError for each one:
class Square:
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
total = 0
for thing in [Square(2), "square", Square(3)]:
try:
area = thing.area
except AttributeError:
print("Skipped", thing)
else:
total += area()
print(total)
# ✅ Expected output:
# Skipped square
# 13Only the lookup, thing.area, sits inside try. The call runs in else, which the except doesn't cover, as Exception Handling showed. So a mistake inside a real area() that raises AttributeError still stops the program, instead of being reported as skipped.
A child must accept what its parent accepts
Code written for the parent will be handed children too, and it calls their methods the parent's way. This child's deposit() wants one more argument than Account's:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be more than 0")
self.balance += amount
class FeeAccount(Account):
def deposit(self, amount, fee):
super().deposit(amount)
self.balance -= fee
def pay_in(accounts, amount):
for acct in accounts:
acct.deposit(amount)
print(acct.owner, acct.balance)
pay_in([Account("Ada"), FeeAccount("Ben")], 50)
# ✅ Expected output:
# Ada 50
# ✅ Expected error:
# TypeError: FeeAccount.deposit() missing 1 required positional argument: 'fee'pay_in() is right for Accounts, and FeeAccount says it is one, yet it can't stand in for one. A default value, as Functions showed, keeps the child compatible:
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be more than 0")
self.balance += amount
class FeeAccount(Account):
def deposit(self, amount, fee=1):
super().deposit(amount)
self.balance -= fee
def pay_in(accounts, amount):
for acct in accounts:
acct.deposit(amount)
print(acct.owner, acct.balance)
pay_in([Account("Ada"), FeeAccount("Ben")], 50)
# ✅ Expected output:
# Ada 50
# Ben 49FeeAccount also takes the fee off after Account's deposit() has checked the amount, so it accepts every amount an Account accepts. Taking the fee off first would make it refuse a deposit of 1, which an Account takes. The same goes for what a method gives back: a child's area() that returned the text "9 square metres" would break every sum of areas. The rule has a name, the Liskov substitution principle: code written for a parent class should work, unchanged, with any of its children.
Is a kind of, or has a
Inherit when the child is a kind of the parent, as a savings account is a kind of account. When one thing only uses another, store the other as an attribute instead:
class Engine:
def start(self):
return "engine running"
class SportsCar(Engine):
pass
class Car:
def __init__(self):
self.engine = Engine()
def start(self):
return "car: " + self.engine.start()
print(SportsCar().start(), isinstance(SportsCar(), Engine))
print(Car().start(), isinstance(Car(), Engine))
# ✅ Expected output:
# engine running True
# car: engine running FalseBoth cars start, but SportsCar claims to be an engine, and gets every method Engine will ever have. Car has an engine and decides what to pass on. Holding an object like this is called composition; Mixins, Multiple Inheritance & OOP Patterns compares the two at length.
Where inheritance goes from here
A class can have more than one parent. Python then searches them in a fixed order, which mro() lists, and with several parents super() means the next class in that order rather than simply the parent. Mixins, Multiple Inheritance & OOP Patterns covers both.
class Walker:
def move(self):
return "walks"
class Swimmer:
def move(self):
return "swims"
class Duck(Walker, Swimmer):
pass
print(Duck().move())
print([cls.__name__ for cls in Duck.mro()])
# ✅ Expected output:
# walks
# ['Duck', 'Walker', 'Swimmer', 'object']Your own errors can join a family too: a class built on ValueError is caught by except ValueError. Custom Exceptions & Exception Chaining builds whole families of them.
class ScoreError(ValueError):
pass
def check(score):
if not 0 <= score <= 100:
raise ScoreError("score must be 0 to 100")
return score
try:
check(120)
except ValueError as e:
print(type(e).__name__, e)
# ✅ Expected output:
# ScoreError score must be 0 to 100- Classes mostly made of data can inherit too: Data Classes & Advanced Class Patterns.
- Making + and * work on your own classes, another kind of polymorphism: Operator Overloading & Custom Behaviours.
- Writing "anything with an area() method" down for a type checker: Type Hints & Static Typing with mypy.
Practice: a manager who earns a bonus
A Manager is an Employee who earns a bonus on top of the salary. Fill the three blanks: the class Manager is built on, and the two calls that reach Employee's versions of __init__ and pay(). Read in order, the hints below the code fill the blanks.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def pay(self):
return self.salary
class Manager(___):
def __init__(self, name, salary, bonus):
___.__init__(name, salary)
self.bonus = bonus
def pay(self):
return ___.pay() + self.bonus
staff = [Employee("Ada", 3000), Manager("Ben", 3500, 500)]
for person in staff:
print(person.name, person.pay())
print(isinstance(staff[1], Employee))
# 👉 replace ___ with Employee
# 👉 replace ___ with super()
# 👉 replace ___ with super()
# ✅ Expected output:
# Ada 3000
# Ben 4000
# TrueRun it before filling anything in, and it stops at class Manager(___): with NameError: name '___' is not defined: the class can't be made until its parent exists.
On your own: characters that take hits differently
Write a Character class for a game, and two kinds of character built on it:
- a Character has a name and health; take_hit(damage) takes the damage off its health, never going below 0, and printing one shows, for example, Ada: 105 health;
- a Knight starts with 120 health and takes half the damage, rounded down;
- a Mage starts with 80 health and takes double the damage.
Make a Character called Villager with 50 health, a Knight called Ada and a Mage called Ben. Hit all three with 30, print them, then hit them with 30 again and print them again. If Ben's health goes below 0, the Mage's take_hit() replaced Character's instead of calling it.
# Villager has 50 health, Ada is a Knight, Ben is a Mage.
# Hit each with 30, print all three, then do it again.
# your code hereclass Character:
def __init__(self, name, health):
self.name = name
self.health = health
def take_hit(self, damage):
self.health = max(self.health - damage, 0)
def __str__(self):
return f"{self.name}: {self.health} health"
class Knight(Character):
def __init__(self, name):
super().__init__(name, 120)
def take_hit(self, damage):
super().take_hit(damage // 2)
class Mage(Character):
def __init__(self, name):
super().__init__(name, 80)
def take_hit(self, damage):
super().take_hit(damage * 2)
party = [Character("Villager", 50), Knight("Ada"), Mage("Ben")]
for hero in party:
hero.take_hit(30)
print(hero)
for hero in party:
hero.take_hit(30)
print(hero)
# ✅ Expected output:
# Villager: 20 health
# Ada: 105 health
# Ben: 20 health
# Villager: 0 health
# Ada: 90 health
# Ben: 0 health
Practice quiz
Animal's __init__ sets self.name, and its speak() returns self.name + " makes a sound". Dog(Animal) has def __init__(self, name, breed): self.breed = breed, with no super() call. A program runs rex = Dog("Rex", "collie"), print(rex.breed), then print(rex.speak()). What happens?
- collie, then Rex makes a sound
- collie, then it stops with AttributeError: 'Dog' object has no attribute 'name'
- It stops at Dog("Rex", "collie") with a TypeError
- collie, then None
Answer: collie, then it stops with AttributeError: 'Dog' object has no attribute 'name'. Dog's __init__ replaced Animal's, so self.name was never set. The error waits until speak() reads it.
Animal's __init__ is def __init__(self, name). Dog is class Dog(Animal): pass. A program runs Dog("Rex", "collie"). What happens?
- A Dog named Rex is made, and the breed is ignored
- It stops with TypeError: Dog.__init__() takes 2 positional arguments but 3 were given
- It stops with TypeError: Animal.__init__() takes 2 positional arguments but 3 were given
- It stops with AttributeError: 'Dog' object has no attribute 'breed'
Answer: It stops with TypeError: Animal.__init__() takes 2 positional arguments but 3 were given. Dog has no __init__, so Python runs Animal's, and the message names the __init__ that refused the extra argument.
Account's deposit() adds to self.balance. CountingAccount(Account) initializes balance and deposit_count to 0, but overrides deposit with def deposit(self, amount): self.deposit_count += 1, and nothing else in that method. After acct = CountingAccount("Ada") and acct.deposit(50), what does print(acct.deposit_count, acct.balance) show?
- 1 50
- 0 50
- It stops with AttributeError
- 1 0
Answer: 1 0. The child's deposit() replaced the parent's, so the money was counted but never added. super().deposit(amount) would add it.
SavingsAccount is built on Account, and savings = SavingsAccount("Ada"). What does print(type(savings) == Account, isinstance(savings, Account)) show?
- True True
- True False
- False True
- False False
Answer: False True. type() gives the object's own class, SavingsAccount. isinstance() also counts the classes it's built on.
Account has fee = 2 and withdraw(self, amount) does self.balance -= amount + self.fee. StudentAccount(Account) says only fee = 0. A student account holding 100 withdraws 10. What is its balance?
- 88
- 90
- 92
- It stops with AttributeError: 'StudentAccount' object has no attribute 'fee'
Answer: 90. self.fee is looked up on the object, then its class, StudentAccount, which has fee = 0, before Account is reached.
Animal's describe() returns self.name + " is an animal". Dog(Animal) has def describe(self): super().describe() + " that barks", with no return. What does print(Dog("Rex").describe()) show?
- None
- Rex is an animal that barks
- Rex is an animal
- It stops with a TypeError
Answer: None. The line builds the text and throws it away. A function without return gives None.
Square has an area() method. A program runs for thing in [Square(3), "square"]: print(thing.area()). What happens?
- 9, and then nothing
- It stops before printing anything, because the list mixes types
- 9, then 0
- 9, then it stops with AttributeError: 'str' object has no attribute 'area'
Answer: 9, then it stops with AttributeError: 'str' object has no attribute 'area'. Python checks for area() only when it calls it, one item at a time. The square works; the string has no area().
Shape's area() is def area(self): return 0. Square(Shape) has __init__(self, side), but overrides area as def area(self, units). A program runs for shape in [Shape(), Square(3)]: print(shape.area()). What happens?
- 0, then it stops with TypeError: Square.area() missing 1 required positional argument: 'units'
- 0, then 9
- 0, then None
- It stops before printing anything, because the two area() methods differ
Answer: 0, then it stops with TypeError: Square.area() missing 1 required positional argument: 'units'. Code written for Shape calls area() with no argument, and Square's needs one. A child should accept everything its parent does.
Continue this course
- Previous: Object-Oriented Programming
- Next: Decorators & Advanced Features — Wrap functions to add behaviour without modifying their code
- Quick reference: Python cheat sheet › Classes
- From the blog: Object-Oriented Programming in Python
Frequently asked questions
Can a class have two methods with the same name and different parameters?
No. A second def with the same name replaces the first, as assigning a name twice keeps the second value. A Greeter with greet(self) and then greet(self, name) has only the second, so greet() with no name stops with TypeError: Greeter.greet() missing 1 required positional argument: 'name'. Give the parameter a default value instead, as Functions showed: def greet(self, name="there").
What does super(SavingsAccount, self) mean in older code?
The same as super() inside a method of SavingsAccount. Python 2 needed the class and the object spelled out; Python 3 fills them in when you write super() in a method, so new code leaves them out.
Can I build a class on list or dict?
Yes. class Playlist(list): gets append(), len() and the rest from list, and you add methods of your own. One catch: operations that make a new list, such as playlist + [1], give a plain list, not a Playlist.
How do I call a grandparent's method?
Each super() goes up one step, so if the parent's method calls super() in turn, the grandparent's runs too. To skip the parent, call the grandparent class's method with the object yourself, for example Animal.describe(self).
Should I check hasattr() before calling a method?
You can: hasattr(thing, "area") is True when thing has an attribute called area, so hasattr("square", "area") is False. Often it reads better to look the method up inside try and catch the AttributeError, as the duck typing section does, or to give every class the method.