Introduction to Object‑Oriented Programming (OOP) in Python: Classes, Objects, Attributes, Methods, Inheritance and Polymorphism
This article explains the core concepts of Python object‑oriented programming, covering class definitions, object creation, attributes, instance, class and static methods, inheritance, and polymorphism, and provides clear code examples for each topic.
Object‑oriented programming (OOP) is a programming paradigm that bundles data and the functions that operate on that data into "objects". In Python, a class serves as a blueprint for objects, defining their attributes (data members) and methods (behaviors).
1. What is a Class?
A class defines the properties and operations that its instances will have. The syntax is:
class ClassName:
# attributes (data members)
# methods (member functions)Example:
class Dog:
"""A simple Dog class"""
def __init__(self, name, age):
"""Initialize name and age"""
self.name = name
self.age = age
def bark(self):
"""Simulate dog barking"""
print(f"{self.name} says: Woof!")
def sit(self):
"""Simulate dog sitting"""
print(f"{self.name} is sitting.")
def roll_over(self):
"""Simulate dog rolling over"""
print(f"{self.name} rolled over!")Key points:
The class keyword defines a class.
Class names usually follow CamelCase.
The special method __init__ is the constructor, automatically called when an object is created.
self refers to the instance itself.
Attributes such as name and age are defined in __init__ and bound to self .
Methods like bark , sit , and roll_over define the actions an object can perform.
2. What is an Object?
An object is an instance of a class. Creating an object allocates memory and runs the class constructor __init__ to initialise its attributes.
object_name = ClassName(arguments)Example:
# Create two Dog instances
my_dog = Dog("Buddy", 3)
your_dog = Dog("Lucy", 1)
# Access attributes
print(f"My dog's name is {my_dog.name} and he is {my_dog.age} years old.")
print(f"Your dog's name is {your_dog.name} and she is {your_dog.age} years old.")
# Call methods
my_dog.bark() # Output: Buddy says: Woof!
your_dog.sit() # Output: Lucy is sitting.Key points:
Use the class name followed by parentheses (and arguments if needed) to create an object.
Each instance has its own independent attribute values.
Use the dot operator ( . ) to access attributes or call methods.
3. Attributes
Attributes are data members that store the state of an object. They can be instance attributes (unique to each object) or class attributes (shared by all instances).
class Dog:
species = "Canis familiaris" # class attribute
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age # instance attribute
print(Dog.species) # Canis familiaris
my_dog = Dog("Buddy", 3)
print(my_dog.name) # Buddy
your_dog = Dog("Lucy", 1)
print(your_dog.species) # Canis familiaris4. Methods
Methods are functions defined inside a class. They can be:
Instance methods – first parameter self , operate on instance data.
Class methods – first parameter cls , operate on the class itself, declared with @classmethod .
Static methods – no implicit first argument, declared with @staticmethod .
class Dog:
species = "Canis familiaris"
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says: Woof!")
@classmethod
def get_species(cls):
return cls.species
@staticmethod
def is_mammal():
return True
my_dog = Dog("Buddy", 3)
my_dog.bark() # Buddy says: Woof!
print(Dog.get_species()) # Canis familiaris
print(Dog.is_mammal()) # True5. Inheritance
Inheritance allows a new class (subclass) to acquire attributes and methods from an existing class (superclass), reducing code duplication.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Generic animal sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
print(f"{self.name} says: Woof!")
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name) # Buddy
print(my_dog.breed) # Golden Retriever
my_dog.speak() # Buddy says: Woof!
animal = Animal("Generic Animal")
animal.speak() # Generic animal soundKey points:
Subclasses inherit all attributes and methods of the parent class.
super() calls the parent’s methods.
Subclasses can override methods to provide specialized behavior.
6. Polymorphism
Polymorphism lets objects of different classes respond to the same method call in their own way.
class Cat:
def speak(self):
print("Meow!")
class Dog:
def speak(self):
print("Woof!")
def animal_sound(animal):
animal.speak()
my_cat = Cat()
my_dog = Dog()
animal_sound(my_cat) # Meow!
animal_sound(my_dog) # Woof!Key points:
The function animal_sound can accept any object that implements a speak method.
Both Cat and Dog provide a speak method with different implementations.
This demonstrates polymorphic behavior.
7. Summary
Classes and objects are the core of Python OOP. Mastering class definitions, object instantiation, attributes, methods, inheritance, and polymorphism enables you to write reusable, maintainable, and extensible code. Further study of private attributes, property decorators, metaclasses, and abstract base classes will deepen your understanding of advanced OOP techniques.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.