Lecture

The Relationship Between Classes and Methods

A method is a function defined inside a class and describes the operations that objects (instances) of the class can perform.

Methods can modify the state of an object or perform tasks associated with the object.

Classes and methods have the following relationship:

  • A class defines methods, which represent the common behaviors shared by all objects created from the class.

  • An object (instance) created from a class can use the methods defined in the class.


Example of Classes and Methods

Example of Classes and Methods
# Define the Animal class class Animal: # Constructor method def __init__(self, name): # Set the name attribute self.name = name # Define the speak method def speak(self): # Use the name attribute to return a string return f"My name is {self.name}." # Example of using the class my_pet = Animal("Buddy") # Outputs: 'My name is Buddy.' print(my_pet.speak())

In the code above, the Animal class has a speak method.

The my_pet object can use the speak method because it is an instance of the Animal class.

Quiz
0 / 1

A method defined in a class cannot change the state of an object.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result