Python Method – Classes, Objects and Functions in Python

Free Python courses 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.

Methods in Python

Python Method

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

‘Diesel’

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.

  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.

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

  1. How many methods are there in Python?
  2. What are built in methods in Python?
  3. How do you create a method in Python?
  4. How do you add a method to a class in Python?
  5. 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.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

10 Responses

  1. Anjal. P says:

    Ioved the way the concepts are presented in here, I was searching for a months for learning python conceptually, and not nearly coding. This is the best site for doing so.
    I would request the developer of this site to create an android app, of this tutorial along with a compiler and some exercise and mcqs, this will help a lot of beganners like me to grab what python really is and how to code by understanding

  2. Krunal says:

    Excellent document

    • DataFlair Team says:

      Your positive feedback always appreciate us. Also don’t forget to check out some python projects.

  3. Allen says:

    There is a misspelling in a paragraph in section 5, namely drit() instead of drift()

  4. Jatin says:

    9. Python Magic Methods

    *The list does not end here*

    Where can i get the full list

  5. Rich Dev says:

    Could someone please edit this article, specifically someone who is a fluent and native speaker of American English. The article has quite a few grammatical mistakes and some foreign non-native usage expressions causing errors for the topic of object-oriented programming in Python. OO programming in Python is very exact in its terminology. This article makes OO significantly harder to understand than it should be. The intent and coverage are good but the explanations and language need work.

    • DataFlair Team says:

      Thank you Rich for bringing these mistakes to our attention. We have made the necessary corrections to our article, making the language much more accessible and resolved the grammatical errors. We kindly request you to take a moment to review the revised version of our article.

Leave a Reply

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