Class Methods
A method is a function that belongs to a class. Methods describe what objects of that class can do.
Note: Every method takes self as its first parameter.
Example
A class with a method:
Output: complete Python program
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello, my name is " + self.name)
p1 = Person("Emil")
p1.greet()
Methods with Parameters
Just as with ordinary functions, you can pass parameters to methods:
Example
A class whose methods take parameters:
Output: complete Python program
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
calc = Calculator()
print(calc.add(5, 3))
print(calc.multiply(4, 7))
Methods Accessing Properties
Through self, a method can read and change its object's properties:
Example
This method reads the object's properties:
Output: complete Python program
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def get_info(self):
return f"{self.name} is {self.age} years old"
p1 = Person("Tobias", 28)
print(p1.get_info())
Methods Modifying Properties
A method is also free to change an object's properties:
Example
This method updates a property value:
Output: complete Python program
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def celebrate_birthday(self):
self.age += 1
print(f"Happy birthday! You are now {self.age}")
p1 = Person("Linus", 25)
p1.celebrate_birthday()
p1.celebrate_birthday()
The __str__() Method
The special __str__() method decides what you see when an object is printed:
Example
Printing an object that has no __str__():
Output: complete Python program
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Emil", 36)
print(p1)
Example
Printing an object that defines __str__():
Output: complete Python program
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age})"
p1 = Person("Tobias", 36)
print(p1)
Multiple Methods
Several methods in one class can work together:
Example
A class with several cooperating methods:
Output: complete Python program
class Playlist:
def __init__(self, name):
self.name = name
self.songs = []
def add_song(self, song):
self.songs.append(song)
print(f"Added: {song}")
def remove_song(self, song):
if song in self.songs:
self.songs.remove(song)
print(f"Removed: {song}")
def show_songs(self):
print(f"Playlist '{self.name}':")
for song in self.songs:
print(f"- {song}")
my_playlist = Playlist("Favorites")
my_playlist.add_song("Bohemian Rhapsody")
my_playlist.add_song("Stairway to Heaven")
my_playlist.show_songs()
Delete Methods
The del keyword can also remove a method from a class:
Example
Remove a method, then try to call it:
Output: complete Python program
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello!")
p1 = Person("Emil")
del Person.greet
p1.greet() # This will cause an error