A method is just a function that’s tied directly to a class and has access to its properties in source . See the take_damage method here:
class Soldier:
health: int = 5
# This is a method that reduces the
# health of the soldier
def take_damage(self, damage: int) -> None:
self.health -= damage
soldier_one = Soldier()
soldier_one.take_damage(2)
print(soldier_one.health)
# prints "3"
soldier_two = Soldier()
soldier_two.take_damage(1)
print(soldier_two.health)
# prints "4"Self
Methods are defined within the class declaration. Their first parameter is always the instance of the class that the method is being called on. By convention, it’s called “self”, and because self is a reference to the object, you can use it to read and update the properties of the object.
Notice that methods are called directly on an object instance using the dot operator:
my_object.my_method()Methods Can Return
If a normal function doesn’t return anything, it’s typically not a very useful function. In contrast, methods often don’t return anything because they can mutate (update) the properties of the object instead.in source
However, they can return values if you want! They’re just functions with access to an object, after all. A common use case is a “getter” method that returns a calculated value based on the properties of the object.
class Soldier:
armor: int = 2
num_weapons: int = 2
def get_speed(self) -> int:
speed = 10
speed -= self.armor
speed -= self.num_weapons
return speed
soldier_one = Soldier()
print(soldier_one.get_speed())
# prints "6"