Python Object Methods

An object method is a function that is defined inside a class and belongs to the objects of that class. We use it to give behaviour to an object, like a Person who can introduce himself or a Car that can start.

Before this chapter, read Python Classes and Objects.


Create an object method

A method looks like a normal function but it is written inside the class, and its first parameter is self. The self parameter points to the current object. (Read what self is if you are not sure.)

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print("Hello, my name is " + self.name)

p1 = Person("John", 36)
p1.introduce()
Output of the above program is

Hello, my name is John

We call the method with a dot, p1.introduce(). Python passes p1 as self by itself, so we do not write it in the brackets.


Methods with parameters and return values

Methods can take arguments and return values like normal functions.

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def resize(self, factor):
        self.width = self.width * factor
        self.height = self.height * factor

r = Rectangle(4, 3)
print(r.area())
r.resize(2)
print(r.area())
Output of the above program is

12
48

The resize() method changes the object itself. After doubling both sides the area becomes four times bigger.


Modify and delete object properties

You can change a property of an object by assigning a new value to it.

p1 = Person("John", 36)
p1.age = 40
print(p1.age)
Output of the above program is

40

To delete a property use the del keyword. You can also delete the whole object.

p1 = Person("John", 36)
del p1.age
print(p1.age)
Output of the above program is

AttributeError: 'Person' object has no attribute 'age'

After del p1.age the property does not exist, so Python raises an error when we try to read it.


The __str__() method

When you print an object, Python shows something like <__main__.Person object at 0x...>. If you add a __str__() method, Python uses it as the text of the object.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return self.name + " (" + str(self.age) + ")"

p1 = Person("John", 36)
print(p1)
Output of the above program is

John (36)


Class methods and static methods

Normal methods work on one object. Python has two other kinds of methods too.

TypeDecoratorFirst parameterUsed for
Instance methodnoneselfWork with one object
Class method@classmethodclsWork with the class itself
Static method@staticmethodnoneUtility function that only lives inside the class
class Student:
    count = 0

    def __init__(self, name):
        self.name = name
        Student.count += 1

    @classmethod
    def total_students(cls):
        return cls.count

    @staticmethod
    def is_valid_name(name):
        return len(name) > 1

Student("Robin")
Student("Maria")
print(Student.total_students())
print(Student.is_valid_name("A"))
Output of the above program is

2
False


Summary

  • A method is a function written inside a class.
  • The first parameter is self, and Python passes it automatically.
  • You can change properties with assignment and remove them with del.
  • Add __str__() to control how an object is printed.
  • Use @classmethod and @staticmethod when the method does not need a single object.
  • Continue with Python Inheritance.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.