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 passesrexin asselffor you
Every method's first parameter is self. When you write rex.describe():
- Python finds
describein theDogblueprint - it runs it with
selfset torex, the object before the dot - so
self.nameinside 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))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():givesTypeError: Dog.bark() takes 0 positional arguments but 1 was givenwhen you calld.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,
nameon its own is a local variable; the object's value isself.name. - Calling it on the class.
Dog.describe()has no object to beself; call it on an object:rex.describe().
Quiz
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())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"))When you call
rex.describe(), what does Python pass asself?- rex
- The Dog class
- Nothing
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])Which line has a mistake?
class Circle: def __init__(self, radius): self.radius = radius def diameter(self): return radius * 2
Coding tasks
Write a class
Circlethat stores aradiusand has a methoddiameter()that returns twice the radius.Write a class
Studentthat stores anameand a list ofmarks, with a methodaverage()that returns the average mark.Write a class
Greeterthat stores agreetingand has a methodgreet(name)returning"<greeting>, <name>!".