Python Method – Classes, Objects and Functions in Python

1. Python Method – Objective

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

2. Introduction to 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 and wherever you encounter any doubt in the Python Method, please ask in the comment.
Learn: Python Inheritance, Method Overloading and Method Overriding

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

Learn: Python Multiple Inheritance – Python MRO (Method Resolution Order)

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

‘Diesel’

Learn: Python Operator Overloading and Python Magic Methods

5. 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')

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.

Learn: Python Counter – Python Collections Type

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.

Learn: Difference Between Method and Function in Python

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

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[/php]

‘Leo’

This was all about the Python Self Parameter

Learn: Comparison Operator in Python with Syntax and Examples

Any doubt yet in Python Method? Please Comment.

8. 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 Interview Questions

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

Learn: Python Jobs – Python Career Opportunities

This was all about the Python Method.

10. Conclusion: Python Method

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. Don’t forget to revise the various methods we discussed in our tutorials on Python lists, tuples, strings, sets, and dictionaries in python. If you have any doubt regarding Python Method, Please Ask.

Reference

2 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

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.