Python Method – Classes, Objects, and Functions in Python
In this tutorial, we'll explore Python methods, class methods, objects, and functions to deepen your understanding of Python programming.
What is a Python Method?
As you may already know, Python is an object-oriented language. This means it supports classes and objects to simulate real-world concepts.
A Python method is essentially a function you call on an object. It is a block of code that operates on that specific object.
Before diving deeper, let’s quickly understand what classes and objects are.
Python Class Method
A class in Python is a blueprint or template for creating objects. For instance, think of a class as a car design plan. Each real-world car built using that design follows the same structure.
Let’s say we have a Car class with properties such as brand, model, color, and fuel type. It may also include behaviors like start(), halt(), drift(), speedup(), and turn().
class Car: def __init__(self, brand, model, color, fuel): self.brand = brand self.model = model self.color = color self.fuel = fuel def start(self): pass def halt(self): pass def drift(self): pass def speedup(self): pass def turn(self): pass
Python Objects
An object is an instance of a class. Using the Car class, we can create an object blackverna like this:
blackverna = Car('Hyundai', 'Verna', 'Black', 'Diesel')
We can access its attributes using the dot . operator:
print(blackverna.fuel) # Output: Diesel
Python Method
A method in Python is similar to a function but is always defined inside a class and must be called on an object.
In our Car class, the methods like start(), halt(), etc., are currently empty using the pass statement. To call a method:
blackverna.drift()
Methods can take parameters and return values, just like functions. Here's another example:
class Try: def __init__(self): pass def printhello(self, name): print(f"Hello, {name}") return name obj = Try() obj.printhello('Ayushi') # Output: Hello, Ayushi
Importance of self Parameter
When calling a method, Python automatically passes the instance (object) as the first argument. That’s why you must include self in method definitions.
If you forget to include self, you’ll get an error like this:
TypeError: drift() takes 0 positional arguments but 1 was given
Recreating the object after fixing the method definitions solves this issue.
__init__() Method
This is Python’s constructor method, automatically called when a class object is created. It’s used to initialize object attributes.
class Animal: def __init__(self, species, gender): self.species = species self.gender = gender fluffy = Animal('Dog', 'Female') print(fluffy.gender) # Output: Female
You don’t always need to define __init__() if not required.
Another Example:
class Try2: def hello(self): print("Hello") obj2 = Try2() obj2.hello()
The __init__() method is a special or “magic” method, identified by double underscores before and after its name.
How self Works
self refers to the current object instance. It's similar to this in Java.
class Fruit: def printstate(self, state): print(f"The orange is {state}") orange = Fruit() orange.printstate("ripe") # Output: The orange is ripe
Another example:
class Result: def __init__(self, phy, chem, math): self.phy = phy self.chem = chem self.math = math def printavg(self): print(f"Average = {(self.phy + self.chem + self.math) / 3}") rollone = Result(86, 95, 85) print(rollone.chem) # Output: 95 rollone.printavg() # Output: Average = 88.66666666666667
You can also set default values directly inside the constructor:
python
class LED: def __init__(self): self.lit = False obj = LED() print(obj.lit) # Output: False
The word self is not a keyword. You can name it anything:
class Try3: def __init__(thisobj, name): thisobj.name = name obj1 = Try3('Leo') print(obj1.name) # Output: Leo
Python Function vs Method
Let’s summarize the key differences:
A method is always called on an object, while a function is standalone.
Methods are tied to objects and can modify object states.
Functions can accept objects as arguments but don’t alter the object’s state unless explicitly programmed to.
Python Magic Methods
Magic methods are special methods with double underscores (also called "dunders").
Some examples:
__add__ for +
__sub__ for -
__mul__ for *
__and__ for &
There are many more we’ll cover in future lessons.
Python Method Interview Questions
How many types of methods exist in Python?
What are built-in methods in Python?
How do you define a method in Python?
How do you add a method to a class?
How do you call a method from another class?
Conclusion
In summary, a Python method behaves similarly to a function but is always associated with an object. Methods are a fundamental part of working with classes and object-oriented programming in Python.
Write A Comment
No Comments