6. OOP
6. OOP
PROGRAMMING
By
Prof. G V S SARMA
Department of Chemical Engineering
Andhra University College of Engineering(A)
Andhra University
CONTENTS
It follows a linear flow of execution and is often used for tasks that
can be broken down into a series of steps.
Drawbacks of Procedural Programming:
1. Ambiguity and Lack of Clarity:
In procedural programming, representing circles using 3-tuples can be
ambiguous.
It's unclear what each element of the tuple represents (e.g., (x, y, radius)
or (radius, x, y)).
Example: circle = (11, 60, 8)
Abstraction:
• Abstraction involves hiding the complex implementation details of a
system while exposing only the relevant features or behaviors.
• It allows developers to focus on essential aspects of an object or system
and ignore unnecessary complexities.
Special Methods:
Example: The _ _add_ _() special method allows objects to support the +
operator for addition.
Methods: Methods are functions defined within a class that operate on the
Properties:
Variable Scope:
Inheritance:
• Inheritance is the mechanism by which a new class (subclass) can
inherit attributes and methods from an existing class (base class
or superclass).
• It allows for code reuse and the extension of existing functionality.
Base Class (Superclass):
The base class is the class from which other classes inherit. It provides the
foundation for the inheritance hierarchy.
The subclass is a class that inherits attributes and methods from a base
class. It can extend or modify the functionality of the base class.
Naming Conventions:
• In Python, naming conventions help maintain consistency and
readability in code.
• Custom classes follow the convention of using an uppercase letter as
the first letter of the class name.
CUSTOM CLASSES
Custom classes can be created using the ‘class’ keyword, which allows
developers to define their own data types with specific attributes and
methods.
Class Suite:
Inheritance:
A class can inherit attributes and methods from one or more base
classes by specifying them inside parentheses after the class name. This
allows for code reuse and promotes modular design.
Dynamic Class Creation:
Class Methods:
Class Instances:
Instances of a class (objects) are created by calling the class with any
required arguments. This invokes the class's constructor method
(__init__), which initializes the object's state.
Example:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def drive(self):
print(f"{self.make} {self.model} is driving.")
• Instances of the Car class are created using the constructor method
(__init__) by passing arguments, and methods are invoked on these
objects to perform specific actions.
Instance Attributes:
Instance attributes are unique to each object and are initialized within
the __init__ method using the ‘self’ keyword.
ATTRIBUTES AND METHODS
Attributes:
2. Class Methods: Class methods operate on the class itself rather than
individual instances. They have access to class attributes but not to
instance attributes. They are defined using the ‘@classmethod’
decorator and have a ‘cls’ parameter as the first parameter.
3. Static Methods: Static methods are independent of class and instance
attributes. They are defined using the ‘@staticmethod’ decorator and
do not have access to ‘self’ or ‘cls’ parameters. Static methods are
primarily used for utility functions that do not require access to instance
or class attributes.
Example:
Simple class, Point, that holds an (x, y) coordinate. The class is defined
in a file named Shape.py
self.y = y
def distance_from_origin(self):
Inheritance
• The class being inherited from is called the base class or superclass,
and the class inheriting from it is called the derived class or subclass.
Example:
class Superclass:
# Superclass definition
class Subclass(Superclass):
# Subclass definition
Polymorphism
• Polymorphism is the ability of different objects to respond to the
same message (method call) in different ways.
class Circle(Point):
def __init__(self, radius, x=0, y=0):
super().__init__(x, y)
self.radius = radius
def edge_distance_from_origin(self):
return abs(self.distance_from_origin() self.radius)
def area(self):
return math.pi * (self.radius ** 2)
def circumference(self):
return 2 * math.pi * self.radius
def __eq__(self, other):
return self.radius == other.radius and super().__eq__(other)
def __repr__(self):
return "Circle({0.radius!r},{0.x!r},{0.y!r})".format(self)
def __str__(self):
return repr(self)
p = Shape.Point(28, 45)
Getter Methods:
Properties are defined using getter methods, which are decorated with
@property.
A getter method retrieves the value of an attribute.
Getter methods allow accessing the value of an attribute in a read-only
manner.
Property Decorator:
The @property decorator is used to define getter methods, making
them accessible as properties.
It provides a concise and clear syntax for defining properties in Python
classes.
Setter Methods:
Properties can also have setter methods, allowing for validation or
modification of attribute values when they are set.
Setter methods are decorated with @<property_name>.setter.
A setter method assigns a new value to an attribute.
Private Attributes:
Properties can be used to access private attributes (attributes prefixed
with double underscores __).
Private attributes are conventionally used to store attribute values
while providing controlled access through properties.
Validation:
Properties can enforce validation rules to ensure that attribute values
meet specific criteria.
Docstrings and Doctests:
Properties can include docstrings and doctests to provide
documentation and test cases for attribute access.
Docstrings describe the purpose and usage of properties, while
doctests provide executable examples to verify property behavior.
Initializer:
Properties can be initialized within the class initializer (__init__
method) to ensure proper attribute setup during object creation.
Example:
class Circle(Point):
self.radius = radius
@property
def area(self):
"""Calculate the area of the circle."""
@property
def edge_distance_from_origin(self):
"""Calculate the distance from the edge of the circle to the origin."""
def radius(self):
return self.__radius
@radius.setter
self.__radius = radius
def distance_from_origin(self):
"""Calculate the distance from the center of the circle to the origin."""
return f"Circle(radius={self.radius})"
circle = Circle(5)
print(circle.radius) # Output: 5
Class Definition:
The Circle class is defined with methods for calculating the area,
edge distance from the origin, and accessing/modifying the radius
attribute.
Properties:
Properties like area, edge_distance_from_origin, and radius are
defined using the @property decorator.
The area and edge_distance_from_origin properties provide computed
values based on the radius.
The radius property encapsulates access to the __radius private
attribute and includes a setter method for validation.
Getter and Setter Methods:
Getter and setter methods are defined using the @property and
@<property_name>.setter decorators, respectively.
The radius property includes getter and setter methods for accessing
and modifying the radius attribute.
Validation:
The setter method for the radius property includes validation to
ensure that the radius value is non-zero and non-negative.
THANK YOU