Skip to main content

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:

Prompt
Write a Python class Person with init that takes name, and a greet method that prints a greeting. Create a Person object and call greet.
Output: complete Python program

Methods with Parameters

Just as with ordinary functions, you can pass parameters to methods:

Example

A class whose methods take parameters:

Prompt
Write a Python class Calculator with add and multiply methods that take two parameters each. Create a Calculator object and print the results of add(5,3) and multiply(4,7).
Output: complete Python program

Methods Accessing Properties

Through self, a method can read and change its object's properties:

Example

This method reads the object's properties:

Prompt
Write a Python class Person with name and age properties, and a get_info method that returns a formatted string. Create a Person and print get_info().
Output: complete Python program

Methods Modifying Properties

A method is also free to change an object's properties:

Example

This method updates a property value:

Prompt
Write a Python class Person with a celebrate_birthday method that increments age and prints a message. Create a Person and call celebrate_birthday twice.
Output: complete Python program

The __str__() Method

The special __str__() method decides what you see when an object is printed:

Example

Printing an object that has no __str__():

Prompt
Write a Python class Person with name and age. Print the object without a str method.
Output: complete Python program

Example

Printing an object that defines __str__():

Prompt
Write a Python class Person with name and age, and a str method returning formatted string. Create a Person and print it.
Output: complete Python program

Multiple Methods

Several methods in one class can work together:

Example

A class with several cooperating methods:

Prompt
Write a Python class Playlist with add_song, remove_song, and show_songs methods. Create a playlist, add two songs, and show them.
Output: complete Python program

Delete Methods

The del keyword can also remove a method from a class:

Example

Remove a method, then try to call it:

Prompt
Write a Python class Person with a greet method. Delete the method using del, then try to call it.
Output: complete Python program