Methods and parameters in Python define how functions and object behaviours work. Methods are functions associated with objects or classes, while parameters are the inputs passed to them allowing flexible, reusable and dynamic code execution. These concepts help organise code and implement object-oriented programming in a clear and reusable way.
Methods
Methods are functions defined inside a class that perform specific tasks related to the class. They allow objects to behave in certain ways and help organize functionality around the data of the class.
1. __init__ Method
__init__ method, also called the constructor, is a special method that is automatically called when a new object of the class is created. Its main purpose is to initialize the attributes of the object.
- Here, when p1 and p2 are created, the __init__ method runs automatically and sets the name and age attributes for each object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print(f"{self.name} is {self.age} years old.")
p1 = Person("Olivia", 25)
p2 = Person("Henry", 26)
Output
Olivia is 25 years old. Henry is 26 years old.
2. Calling Class Methods
Class methods can be called using the class name or an object, followed by a dot (.) and the method name. This executes the method and performs the behavior defined in the class.
- Here the greet method is called on the 'p' object, which executes the function defined in the Person class.
class Person:
def greet(self):
print("Hello!")
p = Person()
p.greet()
Output
Hello!
3. Instance Methods
Instance methods are defined inside a class and operate on instance variables. Every instance method must have self as its first parameter, which refers to the object calling the method.
- Here the run() method is an instance method that uses self to access the object’s name attribute and prints a message indicating that the person is running.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print(f"{self.name} is running.")
p1 = Person("Selena", 25)
p1.run()
Output
Selena is running.
Parameters
Parameters are values that you pass to a method or function to provide input. They allow the method to use different data each time it is called.
1. Self-Parameter
The self-parameter is a reference to the current instance of the class. It is used to access the object’s attributes and other methods from within instance methods. Python automatically passes self when a method is called on an object.
- The display_info method uses self to access the name and age attributes of the p1 object, allowing the method to display the correct information for that specific instance.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
p1 = Person("Harris", 25)
p1.display_info()
Output
Name: Harris, Age: 25
3. Inheritance
Inheritance allows a class to reuse and extend the properties and methods of another class. The class being inherited from is called the parent class and the inheriting class is called the child class.
The following code shows how a child class can inherit properties from a parent class and also define its own unique behavior.
- Boss inherits from the Agent class, so it automatically has access to all methods and attributes of Agent.
- The __init__ method of Agent initializes the name, age, health, and alive attributes when a Boss object is created.
- Methods like curr_health, punched, shooted, is_alive, and info belong to Agent and can be used by Boss.
- The Boss class also defines its own method blow_fire, which is specific to the child class.
class Agent:
def __init__(self, name, age):
print('Welcome to the Game')
self.name = name
self.age = age
self.health = 100
self.alive = True
def curr_health(self):
print('Current Health of', self.name, 'is', self.health)
def punched(self):
self.health -= 10
def shooted(self):
self.health -= 50
def is_alive(self):
if self.health <= 0:
self.alive = False
def info(self):
print('Name : ', self.name)
print('Age : ', self.age)
print('Health : ', self.health)
print('Alive : ', self.alive)
class Boss(Agent):
def blow_fire(self):
print('blow fire!')
bs = Boss('Tayne', 1000)
bs.info()
bs.blow_fire()
Output
Welcome to the Game Name : Tayne Age : 1000 Health : 100 Alive : True blow fire!