08_20241028_OOP
08_20241028_OOP
#Constructor to initialize
def __init__(self,company,color):
self.company = company
self.color = color
#function to print car company and color
def display(self):
print ('This is a', self.color, self.company)
2. Key OOP Terminology and Concepts
Classes and Objects:
Here we have defined a Python class.
First is class declaration followed by documentation string. The docstring can be
accessed using class_ name.__doc__ i.e. car.__doc__
__init__ method
__init__ method is used for the initialization of the data members. This serves
as the constructor for the class and as any function, it can take any number of
arguments.
After __init__ method is another function called display to print the car
company and color as supplied to the function.
2. Key OOP Terminology and Concepts
Classes and Objects:
What is that 'self' variable?
In Python, self is a special variable used in instance methods to
represent the instance of the class on which a method is being
called.
Calling Other Methods: self lets methods call other methods within the
same instance.
Unique to Each Instance: Each instance has its own self reference, so
attributes and methods can be used separately in each instance.
2. Key OOP Terminology and Concepts
Classes and Objects:
What is that 'self' variable?
Well in every method inside a Python class, self is used as the reference to
the object of the class. It is included in a function as a first parameter.
When the function defined inside a class is invoked, self refers to the object
of the class.
def birthday(self):
self.age += 1
print(f"Happy Birthday, {self.name}! You are now {self.age}.")
class Employee:
def __init__(self, name, salary):
self.name = name # Public attribute
self._salary = salary # Private attribute
def give_raise(self, amount):
self._salary += amount
print(f"{self.name}'s new salary: {self._salary}")
# Usage
emp = Employee("John Doe", 50000)
emp.give_raise(5000) # John's new salary: 55000
The private attribute _salary is only modified through the give_raise method, ensuring
data control.
3a. Python built-in class attributes
There are certain built-in class attributes in Python which can be accessed using
a dot(.) operator.
Python class attributes with description
__dict__
Returns a dictionary of classes namespace.
__doc__
Returns the class documentation string, if defined.
__module__
Return the name of the module in which the class is defined.
__name__
Return the name of the class.
The private attribute _salary is only modified through the give_raise method, ensuring
data control.
3a. Python built-in class attributes
Example: to demonstrate how these attributes can be used in the program.
class car:
"A simple class for cars"
#Constructor to initialize
def __init__(self,company,color):
self.company = company
self.color = color #making color private
class Dog(Animal):
def speak(self):
print("Woof Woof!") # Overrides the speak method
class Cat(Animal):
def speak(self):
print("Meow!") # Overrides the speak method
# Demonstrating polymorphism
animals = [Dog(), Cat()]
for animal in animals:
animal.speak() # Outputs "Woof Woof!" and "Meow!" based on the class
4. Inheritance and Method Overriding
Benefits of Inheritance:
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
import math
return math.pi * self.radius ** 2
@property
def area(self):
import math
return math.pi * (self._radius ** 2)
# Usage
circle = Circle(5)
print(circle.radius) # Access radius
print(circle.area) # Access area, calculated as a property
6. Encapsulation and Using Properties
built-in properties
The @property Decorator
The @property decorator allows us to define a method that
behaves like an attribute.
It enables controlled access to private or protected attributes
and allows us to add custom logic when getting or setting an
attribute value.
• Getter: The method decorated with @property acts as a
getter for a private attribute.
• Setter: The method decorated with @attribute_name.setter
allows controlled assignment of values to the attribute.
• Deleter: The method decorated with
@attribute_name.deleter enables deleting the attribute (less
commonly used but available).
6. Encapsulation and Using Properties
Example: Using Properties to Control Attribute Access
class Product:
def __init__(self, name, price):
self.name = name
self._price = price # Private attribute
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("Price cannot be negative.")
self._price = value