In Python, methods are functions that are associated with objects. Unlike standalone functions, which can be called independently, methods are called on objects and operate on the data contained within those objects. Methods are a way to bundle functions with the objects they operate on, providing a way to interact with and manipulate the object's state.
Here are some key points about Python methods:
Object Association:
Accessing Methods:
.
) and the method name.object.method()
Self Parameter:
self
and refers to the instance of the object on which the method is called.class MyClass:
def my_method(self):
# Code inside the method
Built-in Methods:
my_string = "Hello, World!"
print(my_string.upper()) # Calling the upper() method on a string
Custom Methods:
class Circle:
def calculate_area(self, radius):
return 3.14 * radius**2
Mutability:
Function vs. Method:
Here's an example illustrating a method:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
self.fuel = 0
def add_fuel(self, amount):
self.fuel += amount
print(f"{amount} liters of fuel added to the {self.brand} {self.model}.")
# Creating an instance of the Car class
my_car = Car("Toyota", "Camry")
# Calling the add_fuel method on the my_car object
my_car.add_fuel(20)
In this example, add_fuel
is a method of the Car
class, and it is called on an instance of the class (my_car
). The method modifies the fuel
attribute of the my_car
object.
Understanding methods is fundamental to object-oriented programming in Python, as they enable the encapsulation of behavior within objects, leading to more modular and maintainable code.