Python uses the class keyword to define a class. The constructor is __init__(self, ...). self refers to the current instance.
class Animal:
def __init__(self, name, sound):
self.__name = name # private attribute
self.__sound = sound
def get_name(self): # getter
return self.__name
def speak(self):
return self.__name + " says " + self.__sound
class Dog(Animal): # Dog inherits Animal
def __init__(self, name):
super().__init__(name, "Woof") # call parent constructor
def fetch(self):
return self.__name + " fetches the ball!"
super() calls a method from the parent class. Most commonly used in the subclass constructor to call the parent's __init__ and avoid duplicating initialisation code.
Python uses naming conventions rather than strict keywords:
self.name — accessible everywhereself._name — convention; accessible within class and subclassesself.__name — name mangled; not directly accessible outside the classPublic methods to read (get) and modify (set) private attributes. Setters can include validation logic:
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
else:
raise ValueError("Amount must be positive")
UML class diagrams show: class name (top), attributes (middle), methods (bottom). Arrows show inheritance (hollow triangle) and association.
8 questions · instantly marked · AQA 7517 standard
self in a method definition?[2]super() in a subclass constructor. Why is it better than re-writing the parent's initialisation code?[3]self.name, self._name, and self.__name?[3]Shape with a private attribute __colour, a constructor that sets it, and a getter method get_colour().[4]| Term | Definition |
|---|
10 questions · 10 minutes