Methods in Python – Classes, Objects and Functions in Python


1. Objective

Hope you have been having fun so far with your Python practice after our python tutorials each day. After all, you must sharpen your axe every so often if you want the wood. Earlier, we learned about functions in Python. They allow us to attach a name/label to a piece of code to execute again and again, and aid code reusability. Today, we will discuss about methods in python, and how they differ from Python functions.

Methods in Python

2. Introduction to Methods in Python

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 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.

3. Classes in Python

A class, in Python, 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

4. Objects in Python

An 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

‘Diesel’

5. Methods in Python

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() 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')

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 drit() method on blackverna, it gave us this error:
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.

6. __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

‘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.

7. The 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")

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

95

>>> rollone.printavg()

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

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

‘Leo’

8. Functions vs Methods

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.

  1. While a method is called on an object, a function is generic.
  2. 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.
  3. 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.

9. Magic Methods

Another construct that Python provides us with is 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.

10. Conclusion

A 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. Don’t forget to revise the various methods we discussed in our tutorials on Python lists, tuples, strings, sets, and dictionaries in python.

Leave a comment

Your email address will not be published. Required fields are marked *