About Python Classes and Inheritance
Definitions: Class & Inheritance?
A class is a blueprint for creating objects.
Inheritance is a mechanism that allows a class to inherit the properties (or attributes) and methods of an existing class.
Object-Oriented Programming (OOP)
At a basic level, an object are instances of a class, and classes serve as blueprints for creating an instance[1] of those objects.
One way to think of OOP is that is separates our program into multiple 'zones', and gives us a modular approach towards program development.
Basic Class Syntax
class MyClass:
def __init__(self, value):
self.value = value # instance attribute
def method(self):
return f"Value is {self.value}"
How to Create a Class
- You define a class using
class
The Class is created with the class keyword when it is defined; the object is created by calling that class like a function. Within each class, there needs to be an init() constructor function to be triggered when the class is called.
Example:
class Dog:
def __init__(self, name, age):
# Define class attribute
self.name = name
self.age = age
# Define class methods
def bark(self):
return f"{self.name} says woof!"
- The constructor sets up each individual "dog" object when the class function is called.
selfis a convention‑name for the current object instance inside a class.
self
- This is always the first parameter in every method instance, including the constructor function.
- When you call the
class(), Python automatically passes the object instance as the self argument to the class attributes and methods.
- Creating an object from that class
objectInstance = Dog("Fido", 5)
- Once the class exists, you create the object by calling the class like a function:
class() - This will automatically call the
class.__init__()
Attributes and Behaviour of a Class
Creating a new class creates a new type of object. Each class can be defined by its attributes and behaviours (methods). An object can contain any number of methods and data structures used by that object.
Attributes
Properties or data members of a class that describe the state of an object.
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand # Attribute: brand
self.model = model # Attribute: model
Behaviour (Methods)
Represent the actions or functions that objects of the class can perform. They are defined within the class and operate on the attributes of the class.
Example:
class Dog:
def __init__(self, name):
self.name = name # Attribute: name
def bark(self):
print(f"{self.name} barks loudly!") # Behavior: bark
Refers to the actual object created at runtime. Often used interchangeably with object. ↩︎