What is the purpose of `self` in Python class methods?
`self` refers to the instance of the class, allowing access to its attributes and methods. It's a convention but not a keyword; you can name it differently.
self
is a convention used in Python class methods to refer to the instance of the class on which a method is being called. It allows you to access attributes and other methods of the class instance. When you define a method within a class, you must include self
as the first parameter, even if you don't use it in the method body:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f'{self.name} says woof!')
In this example, self.name
refers to the name
attribute of the instance. When you create an instance of Dog
and call bark()
, Python automatically passes the instance as the first argument:
dog = Dog('Rex')
dog.bark() # Output: Rex says woof!
Although self
is not a keyword, it's widely used as a naming convention. You could technically name it anything, but using self
is recommended for clarity and consistency, making your code more understandable to others.