Python self
The "self" keyword in Python is a reference to the current instance of the class. It is used within class methods to access attributes and methods of that instance.
When defining a class, we refer to the current instance using the "self" parameter in method definitions. For example:
class MyClass:
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hello, my name is", self.name)
obj = MyClass("John")
obj.say_hello() # Output: Hello, my name is John
In the above example, "self" is used to refer to the instance of the class being created. It is used to access the "name" attribute of the instance within the "say_hello" method.
It is important to note that "self" is just a convention and can be replaced with any other variable name, but it is recommended to use "self" for clarity and consistency with other Python code.