Python 3D Academyবাংলা

Methods

🌍 In real life. Things don't just have things, they do things. A phone has a battery level (an attribute), and it can ring or charge (actions). In Python, an action an object can do is a method: a function written inside the class.

A handy rule:

  • attributes are nouns: name, age, balance
  • methods are verbs: describe, deposit, ring

The idea in one sentence: a method is a function written inside a class, and obj.method() runs it with self set to that object.

Its words:

  • method: a function that belongs to a class, like describe
  • self: the object the method is running on, always the first parameter
  • calling a method: rex.describe(); Python passes rex in as self for you

Every method's first parameter is self. When you write rex.describe():

  1. Python finds describe in the Dog blueprint
  2. it runs it with self set to rex, the object before the dot
  3. so self.name inside the method means rex's name

The same method works for every dog, each with its own data. Watch the beam go from the blueprint to the dog it runs on:

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

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

    def birthday_message(self):
        return "Happy birthday, " + self.name + "!"

rex = Dog("Rex", 3)
print(rex.describe())
print(rex.birthday_message())

A method can take more values after self, like any function. Think of a cricket scoreboard: a Player object remembers its runs, and summary() builds the line the commentator reads:

class Player:
    def __init__(self, name, runs):
        self.name = name
        self.runs = runs

    def summary(self):
        return self.name + ": " + str(self.runs) + " runs"

    def beats(self, other):
        return self.runs > other.runs

ana = Player("Ana", 54)
bo = Player("Bo", 31)
print(ana.summary())
print(ana.beats(bo))
In ana.beats(bo), self is ana and other is bo.

Forgetting self in a method is a common slip. Python still passes the object in, so it complains that one value too many arrived. The error help explains the fix:

class Dog:
    def bark():
        return "Woof"

rex = Dog()
print(rex.bark())

Why methods? The data and the actions that use it live together in one class, so you never have to pass an object's pieces around by hand, and every object of the class gets the same actions for free. Calling a method costs the same as calling a function: one extra step to find it in the class.

Mistakes and edge cases.

  • Forgetting self in the def. def bark(): gives TypeError: Dog.bark() takes 0 positional arguments but 1 was given when you call d.bark(): Python passed the object in, and there was no parameter for it.
  • Forgetting the brackets. print(d.bark) shows <bound method Dog.bark of ...>, not the result.
  • Using a name without self. Inside a method, name on its own is a local variable; the object's value is self.name.
  • Calling it on the class. Dog.describe() has no object to be self; call it on an object: rex.describe().

Quiz

  1. What does this print?

    class Square:
        def __init__(self, side):
            self.side = side
    
        def area(self):
            return self.side * self.side
    
    print(Square(4).area())
  2. What does this print?

    class Robot:
        def __init__(self, name):
            self.name = name
    
        def say(self, word):
            return self.name + " says " + word
    
    r = Robot("R2")
    print(r.say("beep"))
  3. When you call rex.describe(), what does Python pass as self?

    • rex
    • The Dog class
    • Nothing
  4. What does this print?

    class Pet:
        def __init__(self, name):
            self.name = name
    
        def shout(self):
            return self.name.upper() + "!"
    
    pets = [Pet("kiwi"), Pet("bo")]
    print([p.shout() for p in pets])
  5. Which line has a mistake?

    class Circle:
        def __init__(self, radius):
            self.radius = radius
    
        def diameter(self):
            return radius * 2

Coding tasks

  1. Write a class Circle that stores a radius and has a method diameter() that returns twice the radius.

  2. Write a class Student that stores a name and a list of marks, with a method average() that returns the average mark.

  3. Write a class Greeter that stores a greeting and has a method greet(name) returning "<greeting>, <name>!".