A method is a function that belongs to an object.
class ClassName:
def method_name(self, parameters):
# method code
pass
A method always takes self as its first parameter.
Basic Example
class Zombie:
def __init__(self, name):
self.name = name
def groan(self):
print(f"{self.name}: Graaah! ๐ง")
walker = Zombie("Walker")
walker.groan() # Walker: Graaah! ๐ง
When you call walker.groan(), Python automatically passes walker as self.
Methods with Parameters
class Zombie:
def __init__(self, name, health):
self.name = name
self.health = health
def take_damage(self, damage):
self.health -= damage
print(f"{self.name} took {damage} damage. Health: {self.health}")
walker = Zombie("Walker", 50)
walker.take_damage(20)
# Walker took 20 damage. Health: 30
The method take_damage(self, damage) has 2 parameters but is called with 1 argument โ self is passed automatically.
Methods with Return Values
class Zombie:
def __init__(self, name, health):
self.name = name
self.health = health
def is_alive(self):
return self.health > 0
def attack(self):
import random
return random.randint(5, 15)
walker = Zombie("Walker", 30)
if walker.is_alive():
damage = walker.attack()
print(f"The zombie attacks! Damage: {damage}")
Methods Calling Methods
class Zombie:
def __init__(self, name, health):
self.name = name
self.health = health
def groan(self):
print(f"{self.name}: Graaah!")
def walk(self):
print(f"{self.name} is walking...")
def approach(self):
self.walk() # calling another method
self.groan() # via self
print(f"{self.name} is approaching!")
walker = Zombie("Walker", 50)
walker.approach()
# Walker is walking...
# Walker: Graaah!
# Walker is approaching!
Object Interaction
Methods can modify other objects:
class Human:
def __init__(self, name, health):
self.name = name
self.health = health
self.kills = 0
def attack(self, zombie):
damage = 20
zombie.health -= damage
print(f"{self.name} attacks {zombie.name}! Damage: {damage}")
if zombie.health <= 0:
print(f"{zombie.name} is defeated!")
self.kills += 1
class Zombie:
def __init__(self, name, health):
self.name = name
self.health = health
rick = Human("Rick", 100)
walker = Zombie("Walker", 40)
rick.attack(walker) # Rick attacks Walker! Damage: 20
rick.attack(walker) # Rick attacks Walker! Damage: 20 / Walker is defeated!
print(rick.kills) # 1
Types of Methods
Getters โ return data:
def is_alive(self):
return self.health > 0
def get_status(self):
if self.health > 30:
return "Healthy"
elif self.health > 0:
return "Wounded"
return "Dead"
Setters โ modify data with validation:
def set_health(self, value):
self.health = max(0, value) # can't go below 0
Actions โ perform operations:
def attack(self):
print(f"{self.name} attacks!")
return 10
Common Mistakes
Mistake 1: Forgot self in the method signature
def groan(): # โ TypeError: groan() takes 0 arguments but 1 was given
def groan(self): # โ
Mistake 2: Calling a method without parentheses
damage = walker.attack # โ โ a method object, not the result
damage = walker.attack() # โ
โ calling the method
Best Practices
- Method names should be a verb or question:
attack(),is_alive(),get_status() - One method, one responsibility:
shoot()only shoots, doesn’t reload - Return a value when the caller needs the result
- Use
self.method()to call other methods on the same object
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!