oop¶
class¶
- In Python, classes are the foundation of object-oriented programming (OOP).
- They serve as blueprints for creating objects that encapsulate data (attributes) and functionality (methods).
- The
class
keyword is used to define a class.
class Car:
"""A simple Car class."""
def __init__(self, make, model, year):
"""The car's initializer."""
self.make = make
self.model = model
self.year = year
def accelerate(self):
"""Print a message simulating acceleration."""
print("The car is accelerating!")
# Create objects (instances) of the Car class
my_car = Car("Ford", "Mustang", 2023)
another_car = Car("Toyota", "Camry", 2022)
class Car:
: This line defines a class named Car."""A simple Car class."""
: The docstring describes the class's purpose.def __init__(self, make, model, year):
: This is a special method called the constructor or initializer. It's automatically called when you create an object (instance) of the class. Theself
parameter refers to the object itself. Inside the__init__
method, you typically define the attributes (properties) of the object usingself.attribute_name = value
.def accelerate(self):
: This defines a method namedaccelerate
that can be called on Car objects. Methods are functions defined inside a class to perform specific actions on the object's data.You create objects (instances) of a class using the class name followed by parentheses
my_car = Car("Ford", "Mustang", 2023)
another_car = Car("Toyota", "Camry", 2022)
Each object (like
my_car
andanother_car
) has its own set of attributes (make, model, year) initialized with the provided values.You can access an object's attributes using dot notation (.) followed by the attribute name
print(my_car.make) # Output: Ford
- You can call an object's method using dot notation followed by the method name and parentheses
my_car.accelerate() # Output: The car is accelerating!
- Benefits of Using Classes
- Code Reusability: You can create multiple objects from a single class, reducing code duplication.
- Maintainability: Changes made to the class definition affect all its instances, making updates easier.
- Data Encapsulation: By controlling access to attributes and methods, you can protect data integrity.
- Object-Oriented Design: Classes are fundamental for building complex and well-structured programs using OOP principles.
- Key Points
- Classes provide a way to create objects (instances) that share attributes and behaviors.
- The
__init__
method initializes the object's attributes when it's created. - Methods define the functionality (behavior) associated with the class.
- Objects encapsulate data and functionality, promoting data integrity and modularity.
method¶
- In Python, methods are functions that are defined inside a class to operate on its objects (instances).
- They provide ways to access, modify, or interact with the data (attributes) associated with a particular object.
- Methods are defined within a class using the
def
keyword, similar to regular functions. They typically take the object itself (self
) as the first argument, implicitly referencing the object's data
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
"""This method greets the person by name."""
print(f"Hello, my name is {self.name}!")
def introduce(self, other_person):
"""This method introduces the person to another person."""
print(f"{self.name} says hello to {other_person.name}!")
Explanation
def greet(self):
: This defines a method namedgreet
that takesself
as the first argument. Inside the method, you can access the object's attributes usingself.attribute_name
.def introduce(self, other_person):
: This method demonstrates taking another object (other_person
) as an argument in addition toself
.
Common Types of Methods
Constructor (
__init__
): The special__init__
method is automatically called when you create an object (instance) of the class. It's used to initialize the object's attributes.Accessor Methods: These methods retrieve the values of an object's attributes
def get_name(self):
return self.name
- Mutator Methods: These methods modify the values of an object's attributes
def set_age(self, new_age):
self.age = new_age
- Other Methods: These methods define custom functionalities specific to the class and its objects
- You call methods on objects using dot notation (
.
) followed by the method name and parentheses
person1 = Person("chaitu-ycr", 30)
person1.greet() # Output: Hello, my name is chaitu-ycr!
person1.introduce(Person("Bob", 25)) # Output: chaitu-ycr says hello to Bob!
- Benefits of Using Methods
- Encapsulation: Methods control access to an object's attributes, promoting data integrity.
- Code Organization: Methods group functionalities related to a specific object, making code more organized.
- Reusability: Methods defined within a class can be used by all its instances.
- Key Points
- Methods are functions associated with a class that operate on its objects.
- The
self
parameter in methods refers to the object itself. - Methods provide ways to interact with an object's data, enabling you to perform operations and manipulate its state.