Python course with 57 real-time projects - Learn Python
In our last tutorial, we discussed functions in Python. Today, in this Python Method Tutorial, we will discuss what is a method in Python Programming Language.
Moreover, we will learn Python Class Method and Python Object. Along with this, we will study the python functions.
So, let’s start Python Class and Object.
What is Python Method?
You are aware of the fact that Python is an object-oriented language, right? This means that it can deal with classes and objects to model the real world.
A Python method is a label that you can call on an object; it is a piece of code to execute on that object.
But before we begin getting any deeper, let’s take a quick look at classes and objects.
Python Class Method
A Python Class is an Abstract Data Type (ADT). Think of it like a blueprint. A rocket made from referring to its blueprint is according to plan.
It has all the properties mentioned in the plan, and behaves accordingly. Likewise, a class is a blueprint for an object.
To take an example, we would suggest thinking of a car. The class ‘Car’ contains properties like brand, model, color, fuel, and so.
It also holds behavior like start(), halt(), drift(), speedup(), and turn(). An object Hyundai Verna has the following properties then.
brand: ‘Hyundai’
model: ‘Verna’
color: ‘Black’
fuel: ‘Diesel’
Here, this is an object of the class Car, and we may choose to call it ‘car1’ or ‘blackverna’.
>>> 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
A Python object is an instance of a class. It can have properties and behavior. We just created the class Car.
Now, let’s create an object blackverna from this class.
Remember that you can use a class to create as many objects as you want.
>>> blackverna=Car('Hyundai','Verna','Black','Diesel')
This creates a Car object, called blackverna, with the aforementioned attributes.
We did this by calling the class like a function (the syntax).
Now, let’s access its fuel attribute. To do this, we use the dot operator in Python(.).
>>> blackverna.fuel
Output
Python Method
A Python method is like a Python function, but it must be called on an object.
And to create it, you must put it inside a class.
Now in this Car class, we have five methods, namely, start(), halt(), drift(), speedup(), and turn().
In this example, we put the pass statement in each of these, because we haven’t decided what to do yet.
Let’s call the drift() Python method on blackverna.
>>> blackverna.drift() >>>
Like a function, a method has a name, and may take parameters and have a return statement.
Let’s take an example for this.
>>> class Try: def __init__(self): pass def printhello(self,name): print(f"Hello, {name}") return name >>> obj=Try() >>> obj.printhello('Ayushi')
Output
Hello, Ayushi’Ayushi’
Here, the method printhello() has a name, takes a parameter, and returns a value.
- An interesting discovery– When we first defined the class Car, we did not pass the ‘self’ parameter to the five methods of the class. This worked fine with the attributes, but when we called the drift() method on blackverna, it gave us this error:
Output
Traceback (most recent call last):File “<pyshell#19>”, line 1, in <module>
blackverna.drift()
TypeError: drift() takes 0 positional arguments but 1 was given
From this error, we figured that we were missing the ‘self’ parameter to all those methods.
Then we added it to all of them, and called drift() on blackverna again. It still didn’t work.
Finally, we declared the blackverna object again, and then called drift() on it. This time, it worked without an issue.
Make out of this information what you will.
__init__()
If you’re familiar with any other object-oriented language, you know about constructors.
In C++, a constructor is a special function, with the same name as the class, used to initialize the class’ attributes.
Here in Python, __init__() is the method we use for this purpose.
Let’s see the __init__ part of another class.
>>> class Animal: def __init__(self,species,gender): self.species=species self.gender=gender >>> fluffy=Animal('Dog','Female') >>> fluffy.gender
Output
‘Female’
Here, we used __init__ to initialize the attributes ‘species’ and ‘gender’.However, you don’t need to define this function if you don’t need it in your code.
>>> class Try2: def hello(self): print("Hello") >>> obj2=Try2() >>> obj2.hello()
Init is a magic method, which is why it has double underscores before and after it.
We will learn about magic methods in a later section in this article.
Python Self Parameter
You would have noticed until now that we’ve been using the ‘self’ parameter with every method, even the __init__().
This tells the interpreter to deal with the current object. It is like the ‘this’ keyword in Java.
Let’s take another code to see how this works.
>>> class Fruit: def printstate(self,state): print(f"The orange is {state}") >>> orange=Fruit() >>> orange.printstate("ripe")
Output
The orange is ripe
As you can see, the ‘self’ parameter told the method to operate on the current object, that is, orange.
Let’s take 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) >>> rollone.chem
Output
95
>>> rollone.printavg()
Output
Average=88.66666666666667
You can also assign values directly to the attributes, instead of relying on arguments.
>>> class LED: def __init__(self): self.lit=False >>> obj=LED() >>> obj.lit
Output
False
Finally, we’d like to say that ‘self’ isn’t a keyword.
You can use any name instead of it, provided that it isn’t a reserved keyword, and follows the rules for naming an identifier.
>>> class Try3: def __init__(thisobj,name): thisobj.name=name >>> obj1=Try3('Leo') >>> obj1.name
Output
‘Leo’
This was all about the Python Self Parameter
Python Functions vs Method
We think we’ve learned enough about methods by now to be able to compare them to functions.
A function differs from a method in the following ways.
- While a method is called on an object, a function is generic.
- Since we call a method on an object, it is associated with it. Consequently, it is able to access and operate on the data within the class.
- A method may alter the state of the object; a function does not, when an object is passed as an argument to it. We have seen this in our tutorial on tuples.
Python Magic Methods
Another construct that Python provides us with is Python magic methods. Such a method is identified by double underscores before and after its name.
Another name for a magic method is a dunder.
A magic method is used to implement functionality that can’t be represented as a normal method.
__init__() isn’t the only magic method in Python; we will read more about it in a future lesson.
But for now, we’ll just name some of the magic methods:
__add__ for +
__sub__ for –
__mul__ for *
__and__ for &
The list, however, does not end here.
This was all about the Python Method.
Python Interview Questions on Methods
- How many methods are there in Python?
- What are built in methods in Python?
- How do you create a method in Python?
- How do you add a method to a class in Python?
- How do you call a method from one class to another in Python?
Conclusion
A Python method, as we know it, is much like a function, except for the fact that it is associated with an object.
Now you know how to define a method, and make use of the __init__ method and the self-parameter, or whatever you choose to call it.