Python OOP Concepts Tutor
This tutor guide is designed to teach Python Object-Oriented Programming (OOP) concepts using
w3schools.com as the primary source. It covers the fundamental principles of OOP in Python, including
classes, objects, inheritance, polymorphism, encapsulation, and abstraction. Each section includes key
characteristics, example usage, and references to w3schools.com for detailed tutorials and interactive
examples.
1. Introduction to OOP in Python
Object-Oriented Programming (OOP) is a programming paradigm that organizes code using objects and
classes, making it easier to manage and reuse. Python, as an object-oriented language, supports OOP to
create structured, maintainable, and scalable applications.
Why Learn OOP?
Provides a clear structure for programs.
Enhances code maintenance, reusability, and debugging.
Follows the DRY (Don't Repeat Yourself) principle.
Enables building reusable applications with less code.
Reference: Python OOP
2. Classes and Objects
Classes are user-defined data types that serve as blueprints for creating objects. Objects are instances of
classes that hold specific data and can perform actions defined by the class.
a. Creating a Class
Use the class keyword to define a class.
Example:class MyClass:
x=5
Reference: Python Classes
Practice: Try it at Class Creation
b. Creating an Object
Instantiate an object using the class name.
Example:p1 = MyClass()
print(p1.x) # Output: 5
Reference: Python Classes
Practice: Try it at Object Creation
c. The __init__() Function
The __init__() function initializes object properties when an object is created.
Example:class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name) # Output: John
Reference: Python Classes
Practice: Try it at init Function
d. The __str__() Function
The __str__() function defines the string representation of an object.
Example:class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1) # Output: John(36)
Reference: Python Classes
Practice: Try it at str Function
e. Object Methods
Methods are functions defined within a class that operate on its objects.
Example:class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc() # Output: Hello my name is John
Reference: Python Classes
Practice: Try it at Object Methods
f. The self Parameter
The self parameter refers to the current instance of the class, used to access its attributes and methods.
Example:class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc() # Output: Hello my name is John
Reference: Python Classes
Practice: Try it at self Parameter
g. Modifying Object Properties
Object properties can be modified directly.
Example:p1.age = 40
Reference: Python Classes
Practice: Try it at Modify Properties
h. Deleting Object Properties
Use the del keyword to remove properties.
Example:del p1.age
Reference: Python Classes
Practice: Try it at Delete Properties
i. Deleting Objects
Use the del keyword to delete an object.
Example:del p1
Reference: Python Classes
Practice: Try it at Delete Objects
3. Inheritance
Inheritance allows a class (child) to inherit methods and properties from another class (parent),
promoting code reuse.
a. Parent Class
Any class can serve as a parent class.
Example:class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname() # Output: John Doe
Reference: Python Inheritance
Practice: Try it at Parent Class
b. Child Class
A child class inherits from a parent class using the parent class name in parentheses.
Example:class Student(Person):
pass
x = Student("Mike", "Olsen")
x.printname() # Output: Mike Olsen
Reference: Python Inheritance
Practice: Try it at Child Class
c. Adding the __init__() Function
The child class can define its own __init__() function, calling the parent’s __init__() explicitly.
Example:class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("Mike", "Olsen")
x.printname() # Output: Mike Olsen
Reference: Python Inheritance
Practice: Try it at Child init
d. Using the super() Function
The super() function calls the parent class’s methods, including __init__().
Example:class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
print(x.graduationyear) # Output: 2019
Reference: Python Inheritance
Practice: Try it at super() Function
e. Adding Properties
Child classes can add new properties.
Example:class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
print(x.graduationyear) # Output: 2019
Reference: Python Inheritance
Practice: Try it at Add Properties
f. Adding Methods
Child classes can add new methods or override parent methods.
Example:class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("Mike", "Olsen", 2019)
x.welcome() # Output: Welcome Mike Olsen to the class of 2019
Reference: Python Inheritance
Practice: Try it at Add Methods
4. Polymorphism
Polymorphism allows methods to perform different actions based on the object calling them, enhancing
flexibility.
a. Function Polymorphism
Built-in functions like len() work differently for various data types.
Example:print(len("Hello, World!")) # Output: 13
print(len([10, 20, 30])) # Output: 3
Reference: Python Polymorphism
Practice: Try it at Function Polymorphism
b. Class Polymorphism
Different classes can have methods with the same name but different implementations.
Example:class Car:
def move(self):
print("I am moving on 4 wheels")
class Boat:
def move(self):
print("I am moving on water")
car = Car()
boat = Boat()
for x in (car, boat):
x.move()
# Output:
# I am moving on 4 wheels
# I am moving on water
Reference: Python Polymorphism
Practice: Try it at Class Polymorphism
c. Inheritance Polymorphism
Child classes can override parent class methods to provide specific implementations.
Example:class Vehicle:
def move(self):
print("I am moving")
class Car(Vehicle):
def move(self):
print("I am moving on 4 wheels")
car = Car()
car.move() # Output: I am moving on 4 wheels
Reference: Python Polymorphism
Practice: Try it at Inheritance Polymorphism
5. Encapsulation
Encapsulation involves bundling data and methods within a class and restricting access to some
components to protect data integrity.
Python achieves encapsulation using naming conventions: a single underscore (_) for protected variables
and double underscores (__) for private variables (name mangling).
Example:class MyClass:
def __init__(self):
self.__private_var = "I am private"
def get_private_var(self):
return self.__private_var
obj = MyClass()
print(obj.get_private_var()) # Output: I am private
# print(obj.__private_var) # Raises an error due to name mangling
Note: Python’s private variables are not strictly private but use name mangling to discourage direct
access.
Reference: Python Classes
6. Abstraction
Abstraction hides complex implementation details, exposing only the necessary features through a
simplified interface.
In Python, abstraction is achieved through class design, where methods provide a user-friendly interface
without revealing internal workings.
Example:class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def add(self, other):
return ComplexNumber(self.real + other.real, self.imag + other.imag)
def __str__(self):
return f"{self.real} + {self.imag}i"
c1 = ComplexNumber(1, 2)
c2 = ComplexNumber(3, 4)
c3 = c1.add(c2)
print(c3) # Output: 4 + 6i
The user interacts with the add method without needing to understand the internal logic of complex
number addition.
Reference: Inherent in class design, covered indirectly in Python Classes
7. Additional Resources
Interactive Examples: w3schools.com offers “Try it Yourself” examples for each concept, accessible via
the links provided in each section.
Related Topics: Explore related Python topics like modules and iterators at Python Tutorial.
Exercises: Practice OOP with exercises at Python Exercises.
8. How to Use This Tutor
Step 1: Start with the introduction to understand the role of OOP in Python.
Step 2: Study classes and objects to build a strong foundation.
Step 3: Learn about inheritance and how to create child classes.
Step 4: Understand polymorphism and how methods can behave differently for different objects.
Step 5: Explore encapsulation and abstraction to learn how to manage data access and complexity.
Step 6: Use the “Try it Yourself” examples on w3schools.com for hands-on practice.
9. Summary Table of OOP Concepts
Concept
Description
Reference
Classes
Blueprints for creating objects
Python Classes
Objects
Instances of classes
Python Classes
Inheritance
Allows child classes to inherit from parent classes
Python Inheritance
Polymorphism
Methods can do different things based on the object
Python Polymorphism
Encapsulation
Bundling data and methods, restricting access
Python Classes
Abstraction
Hiding complex implementation details
Inherent in class design.