0% found this document useful (0 votes)
33 views10 pages

Python OOP: Classes, Inheritance, Methods

The document provides an overview of Object-Oriented Programming (OOP) in Python, detailing its advantages and key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and inner classes. It explains how to create classes and objects, the significance of the __init__() method, and the use of the self parameter. Additionally, it covers class properties, methods, and how to implement encapsulation through private and protected attributes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views10 pages

Python OOP: Classes, Inheritance, Methods

The document provides an overview of Object-Oriented Programming (OOP) in Python, detailing its advantages and key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and inner classes. It explains how to create classes and objects, the significance of the __init__() method, and the use of the self parameter. Additionally, it covers class properties, methods, and how to implement encapsulation through private and protected attributes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Object-Oriented Programming (OOP)

OOP stands for Object-Oriented Programming. It's a way of programming that structures code
around objects (which have properties and behaviors) rather than simple functions and logic.
Python is an object-oriented language, and almost everything in Python is an object.
Advantages of OOP:
• Provides a clear structure to programs.
• Makes code easier to maintain, reuse, and debug (it helps keep your code DRY - "Don't
Repeat Yourself").
• Allows you to build complex, reusable applications with less code.

1. Classes and Objects


• Class: A blueprint or "object constructor" for creating objects. It defines what properties
(variables) and methods (functions) the object will have.
• Object: An instance of a class. It's the actual "thing" created from the blueprint, with its
own specific data.
Creating a Class
You create a class using the class keyword.
Python
class MyClass:
x = 5 # This is a class property
• The pass Statement: Class definitions cannot be empty. If you have no content, use pass
to avoid an error.
Python
class Person:
pass
Creating an Object (Instantiation)
You create an object (or "instance") by calling the class name as if it were a function.
Python
p1 = MyClass() # p1 is an object of type MyClass
print(p1.x) # Access the object's properties
Output: 5
2. The __init__() Method (The Constructor)
All classes have a built-in method called __init__().
• It is called automatically every time a new object is created from the class.
• It's used to initialize the object, typically by assigning values to its properties.
Python
class Person:
# The __init__ method is the constructor
def __init__(self, name, age):
# '[Link]' and '[Link]' are object properties
[Link] = name
[Link] = age

# When you create this object, __init__ runs


p1 = Person("Emil", 36)

print([Link])
print([Link])
Output:
Emil
36
You can also provide default values for parameters in __init__().
Python
class Person:
def __init__(self, name, age=18):
[Link] = name
[Link] = age

p1 = Person("Tobias") # Age will default to 18


print(f"{[Link]} is {[Link]} years old.")
# Output: Tobias is 18 years old.

3. The self Parameter


The self parameter is a reference to the current instance (object) of the class.
• It must be the first parameter of any method in the class, including __init__().
• You use self to access the object's own properties and methods (e.g., [Link]).
Note: self is the standard convention. While you could name it something else (like myobject), it
is strongly recommended to always use self to avoid confusing other developers.
Python
class Person:
def __init__(self, name, age):
# 'self' refers to the specific object being created
[Link] = name
[Link] = age

def greet(self):
# 'self' is used to access this object's 'name'
print("Hello, my name is " + [Link])

p1 = Person("Emil", 25)
[Link]() # 'self' is passed automatically
Output: Hello, my name is Emil

4. Class Properties (Attributes)


Properties are variables that belong to a class.
• Instance Properties: These are unique to each object. They are defined inside __init__()
using the self keyword.
Python
p1 = Person("Emil", 25) # [Link] is "Emil"
p2 = Person("Tobias", 30) # [Link] is "Tobias"
• Class Properties: These are shared by all objects (instances) of the class. They are
defined outside of any method.
Python
class Person:
species = "Human" # Class property

def __init__(self, name):


[Link] = name # Instance property

p1 = Person("Emil")
p2 = Person("Tobias")
print([Link]) # Output: Human
print([Link]) # Output: Human
You can access properties with dot notation ([Link]), modify them ([Link] = 26), and delete
them (del [Link]).

5. Class Methods
Methods are functions that belong to a class. They define the behavior of an object.
• The __str__() Method: This is a special method that controls what gets returned when
you print() the object.
Python
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

# This controls the print() output


def __str__(self):
return f"{[Link]} ({[Link]})"

def celebrate_birthday(self):
[Link] += 1
print(f"Happy birthday {[Link]}! You are now {[Link]}.")

p1 = Person("Tobias", 36)
print(p1) # __str__() is called automatically
p1.celebrate_birthday()
Output:
Tobias (36)
Happy birthday Tobias! You are now 37.

The Pillars of OOP


6. Inheritance
Inheritance allows a Child class (or "derived class") to inherit all the methods and properties
from a Parent class (or "base class").
• Parent Class: The class being inherited from.
• Child Class: The class that inherits.
Python
# Create a Parent Class
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link])

# Create a Child Class that inherits from Person


class Student(Person):
pass # 'pass' means this class is empty for now
x = Student("Mike", "Olsen")
[Link]()
Output: Mike Olsen
Overriding __init__ and using super()
If the child class has its own __init__(), it overrides the parent's __init__(). To keep the parent's
__init__ functionality, you must call it using super().
super() refers to the parent class.
Python
class Student(Person):
def __init__(self, fname, lname, year):
# Call the parent's __init__ method
super().__init__(fname, lname)
# Add new properties for the child
[Link] = year

def welcome(self):
print(f"Welcome {[Link]} {[Link]} to the class of {[Link]}")

x = Student("Mike", "Olsen", 2019)


[Link]()
[Link]()
Output:
Mike Olsen
Welcome Mike Olsen to the class of 2019

7. Polymorphism
Polymorphism means "many forms." In programming, it refers to methods/functions that can be
executed on many different objects or classes.
• Function Polymorphism: A built-in function like len() works on many types (strings,
lists, dictionaries).
Python
print(len("Hello")) # Output: 5
print(len(["apple", "banana"])) # Output: 2
• Class Polymorphism: Multiple classes can have the same method name.
Python
class Car:
def move(self):
print("Drive!")

class Boat:
def move(self):
print("Sail!")

class Plane:
def move(self):
print("Fly!")

car1 = Car()
boat1 = Boat()
plane1 = Plane()

# Because of polymorphism, we can loop and call .move()


for x in (car1, boat1, plane1):
[Link]()
Output:
Drive!
Sail!
Fly!
8. Encapsulation
Encapsulation is about protecting data inside a class and controlling how it's accessed. This
prevents accidental changes to your data.
• Protected (_ single underscore): This is just a convention. It tells other programmers,
"You shouldn't touch this variable directly," but Python doesn't stop you.
Python
self._salary = 50000 # Protected convention
• Private (__ double underscore): This is enforced by Python. It makes the property
inaccessible from outside the class. Python does this by "name mangling" (e.g., __age
becomes _Person__age).
Python
class Person:
def __init__(self, name, age):
[Link] = name
self.__age = age # Private property

p1 = Person("Emil", 25)
# print(p1.__age) # This will cause an AttributeError
To access or change private properties, you use getter and setter methods.
Python
class Person:
def __init__(self, name, age):
[Link] = name
self.__age = age # Private

# A "getter" method
def get_age(self):
return self.__age

# A "setter" method
def set_age(self, age):
if age > 0:
self.__age = age
else:
print("Age must be positive")

p1 = Person("Tobias", 25)

# Get the age using the getter


print(p1.get_age()) # Output: 25

# Set the age using the setter


p1.set_age(26)
print(p1.get_age()) # Output: 26

9. Inner Classes
An inner class is a class defined inside another class. It's useful for grouping helper classes that
are only used by the outer class.
To create an object of the inner class, you must first create an object of the outer class.
Python
class Car:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
[Link] = [Link]() # Create an instance of the inner class

def drive(self):
if [Link] == "Running":
print(f"Driving the {[Link]} {[Link]}")
else:
print("Start the engine first!")
# This is the inner class
class Engine:
def __init__(self):
[Link] = "Off"

def start(self):
[Link] = "Running"
print("Engine started")

def stop(self):
[Link] = "Off"
print("Engine stopped")

car = Car("Toyota", "Corolla")


[Link]()
[Link]()
[Link]()
Output:
Start the engine first!
Engine started
Driving the Toyota Corolla

You might also like