self
(argument)
In Python, self
is a widely followed convention for naming the first argument in instance methods within a class. It represents the instance on which the method is being called, allowing access to instance attributes and methods.
Note: Although you can technically name this argument anything, using self
is a strongly recommended convention. This makes your code more readable and familiar to other Python programmers.
When defining instance methods, the self
argument provides access to the instance. This allows the method to modify the instance’s state and differentiate instance variables from local variables inside methods. While you must explicitly declare self
in method definitions, Python automatically passes the instance to methods when you call them.
Example
Here’s an example demonstrating self
in a class:
dogs.py
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} says Woof!")
# Usage
dog = Dog("Buddy")
dog.speak() # Output: Buddy says Woof!
In this example, self.name = name
assigns the name
attribute to the instance. When you call dog.speak()
, Python implicitly passes dog
as self
, allowing the method to access self.name
and print the expected output.
Related Resources
Tutorial
Object-Oriented Programming (OOP) in Python
In this tutorial, you'll learn all about object-oriented programming (OOP) in Python. You'll learn the basics of the OOP paradigm and cover concepts like classes and inheritance. You'll also see how to instantiate an object from a class.
For additional information on related topics, take a look at the following resources:
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- 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)