

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Classes
incomplete
2: Methods
incomplete
3: Methods Can Return
incomplete
4: Methods vs. Functions
incomplete
5: Constructors
incomplete
6: Constructor Quiz
incomplete
7: Multiple Objects
incomplete
8: Objects Quiz
incomplete
9: Archer Practice
incomplete
10: Class Variables vs. Instance Variables
incomplete
11: Classes Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
You know what a function is, and a method is the exact same thing, it's just tied directly to a class and has access to the properties of the object.
A method automagically receives the object it was called on as its first parameter:
class Soldier:
health: int = 100
def take_damage(self, damage: int, multiplier: int) -> None:
# "self" is dalinar in the first example
#
damage = damage * multiplier
self.health -= damage
dalinar = Soldier()
# "damage" and "multiplier" are passed explicitly as arguments
# 20 and 2, respectively
# "dalinar" is passed implicitly as the first argument, "self"
dalinar.take_damage(20, 2)
print(dalinar.health)
# 60
adolin = Soldier()
# Again, "adolin" is passed implicitly as the first argument, "self"
# "damage" and "multiplier" are passed explicitly as arguments
adolin.take_damage(10, 3)
print(adolin.health)
# 70
A method can operate on data that is contained within the class. In other words, you won't always see all the "outputs" in the return statement because the method might just mutate the object's properties directly.
Because functions are more explicit, some developers argue that functional programming is better than object-oriented programming. Neither paradigm is "better" (I'm required to say this as an educator). The best developers learn and understand both styles and use them as they see fit.
While methods are more implicit (an object's properties are changed from within), they also make it easier to group a program's data and behavior in one place, which can lead to a more organized codebase. It's tradeoffs all the way down.