method
In Python, a method is a function that is associated with a particular object or class. Methods are typically defined within a class and can be called on objects of that class.
Methods define the behaviors and actions that an object of a class can perform. Methods can take arguments. When you call a method on an instance, Python automatically passes that instance as the method’s first argument, which is conventionally named self. That reference is what allows the method to access and modify the object’s attributes.
Methods are a fundamental part of object-oriented programming in Python. They enable encapsulation and the manipulation of an object’s state.
Example
Here’s an example of a method within a class:
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says Woof!"
# Usage
dog = Dog("Buddy")
print(dog.speak()) # Output: Buddy says Woof!
In this example, the .speak() method is defined within the Dog class and can be called on any instance of Dog. When dog.speak() is called, it returns the string "Buddy says Woof!", demonstrating how methods can interact with object attributes.
Related Resources
Tutorial
Python Classes: The Power of Object-Oriented Programming
Learn how to define and use Python classes to implement object-oriented programming. Dive into attributes, methods, inheritance, and more.
For additional information on related topics, take a look at the following resources:
- Python's Instance, Class, and Static Methods Demystified (Tutorial)
- Defining Your Own Python Function (Tutorial)
- Python's Magic Methods in Classes (Course)
- OOP Method Types in Python: @classmethod vs @staticmethod vs Instance Methods (Course)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Python's Instance, Class, and Static Methods Demystified (Quiz)
- Defining and Calling Python Functions (Course)
- Defining and Calling Python Functions (Quiz)
- Defining Your Own Python Function (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.