Python Programming – UNIT 4
Object-Oriented Programming (OOP) in Python:
Introduction to Classes in Python :
In Python, a class is a blueprint or template for creating objects
(instances). It serves as a prototype that defines the attributes (data)
and methods (functions) that objects of that class will possess.
Classes provide a way to structure and organize code by grouping
related data and functionality together.
Creating a Class:
To create a class in Python, use the class keyword followed by the
class name. Inside the class block, you can define attributes and
methods.
Explanation:
The Car class is defined with attributes brand and model, and a
method display_info.
The display_info method prints the brand and model of the
car.
An instance my_car of the Car class is created using the class
name followed by parentheses.
The instance my_car can access the class attributes and
methods using dot notation (my_car.brand,
my_car.display_info()).
Key Concepts:
1. Encapsulation: Classes encapsulate data (attributes) and
behavior (methods) into a single unit, promoting modularity
and reusability.
2. Inheritance: Classes can inherit attributes and methods from
other classes, allowing for code reuse and hierarchical
organization.
3. Polymorphism: Classes can implement methods with the same
name but different functionality, enabling flexibility and
dynamic behavior.
4. Abstraction: Classes abstract away implementation details,
allowing users to interact with objects at a higher level of
abstraction.
Methods in Python Classes
In Python, a method is a function that is defined inside a class and
operates on the attributes of the class or performs specific tasks
related to the class. Methods are analogous to functions but are
associated with a particular class and can access the attributes and
other methods of the class through the self parameter.
Creating Methods:
To create a method in a class, define a function inside the class block.
The first parameter of the method should always be self, which
represents the instance of the class and allows access to its
attributes and methods.
Explanation:
The Person class defines two methods: __init__ and greet.
The __init__ method is a special method (constructor) called
when a new instance of the class is created. It initializes the
attributes name and age.
The greet method prints a greeting message using the
instance's name and age attributes.
Types of Methods:
1. Instance Methods: Instance methods are bound to the instance
of the class and can access and modify instance attributes. They
require the self parameter.
2. Class Methods: Class methods are bound to the class itself
rather than the instance and can access class-level variables
and methods using the cls parameter. They are defined using
the @classmethod decorator.
3. Static Methods: Static methods are not bound to either the
instance or the class and are independent functions defined
inside the class. They do not require the self or cls parameter
and are defined using the @staticmethod decorator.
Class Object in Python:
In Python, a class object is an instance of the class itself. It
represents the class and provides access to its attributes and
methods. Class objects are used to interact with class-level
variables and methods, as well as to create new instances of
the class.
Accessing Class-Level Variables:
Class objects can access class-level variables, which are
variables shared by all instances of the class. These variables
are defined within the class but outside of any method and are
accessed using the class name or the class object.
Accessing Class-Level Methods:
Class objects can also access class-level methods, which are
methods defined within the class using the @classmethod
decorator. These methods operate on class-level variables and
are accessed using the class name or the class object.
Creating Instances of the Class:
Class objects are used to create new instances of the class by
calling the class object as if it were a function. This creates a
new instance of the class, which can then be used to access
instance attributes and methods.
Class as Abstract Data Type (ADT) in Python:
In Python, a class acts as an Abstract Data Type (ADT), providing
a blueprint for organizing data and operations. It encapsulates
data (attributes) and behavior (methods), allowing users to
interact with objects at a higher level of abstraction.
Encapsulation:
Classes encapsulate data and behavior into a single unit, hiding
implementation details. Users interact with objects through
methods without needing to know how data is stored
internally.
Benefits:
1. Abstraction: Users interact with objects through a well-defined
interface without needing to understand internal details.
2. Modularity: Classes organize related data and behavior, making
code easier to understand and maintain.
3. Reusability: Classes can be reused across different parts of a
program, reducing code duplication.
4. Polymorphism: Classes support polymorphism, enabling
flexibility by allowing different classes to implement the same
interface.
Date Class in Python:
In Python, the datetime module provides classes for working with
dates and times. One of the fundamental classes in this module is the
date class, which represents a date in the Gregorian calendar.
Creating Date Objects:
You can create a date object using the date(year, month, day)
constructor, specifying the year, month, and day as arguments.
Accessing Attributes:
The date object has three attributes: year, month, and day, which
represent the components of the date.
Accessing Attributes Using Functions in Python:
In Python, the getattr(), hasattr(), and delattr() functions provide a
way to access, check for existence, and delete attributes of an object
dynamically, respectively.
1. getattr(object, name[, default]):
This function returns the value of the attribute named name of the
specified object. If the attribute does not exist, it raises an
AttributeError unless a default value is provided.
2. hasattr(object, name):
This function checks if the specified object has an attribute named
name. It returns True if the attribute exists, otherwise False.
3. delattr(object, name):
This function deletes the attribute named name from the specified
object. If the attribute does not exist, it raises an AttributeError.
Benefits:
1. Dynamic Attribute Handling: These functions allow you to
manipulate attributes of an object dynamically at runtime.
2. Error Handling: They provide a convenient way to handle
attribute-related errors, such as checking for existence before
accessing or deleting an attribute.
3. Flexibility: Using these functions, you can write more flexible
and dynamic code that adapts to different situations and
conditions.
Built-in Class Attributes of Class Object:
In Python, class objects have several built-in attributes that provide
information about the class itself. These attributes are accessible
using dot notation and are prefixed with double underscores (__),
commonly known as dunder (double underscore) attributes.
1. __dict__:
This attribute is a dictionary containing the namespace of the class. It
maps attribute names (as keys) to their corresponding values. You
can use it to access or modify class attributes dynamically.
2. __doc__:
This attribute contains the documentation string (docstring) of the
class. It provides a description of the class and its purpose, typically
specified as a string literal within triple quotes (""").
3. __name__:
This attribute contains the name of the class. It provides the
identifier used to reference the class within the Python code.
4. __module__:
This attribute contains the name of the module in which the class is
defined. It provides the module namespace to which the class
belongs.
Note: These built-in class attributes are mainly used for introspection
and reflection purposes, allowing you to examine and manipulate
classes and their attributes dynamically at runtime. They provide
valuable information about the structure and properties of Python
classes, facilitating advanced programming techniques and
debugging tasks.