Python Class provides the
self in order to use the internal variables and methods of the class. The self is very useful because it provides direct access without any extra definition. If the self keyword is not used a global variable or function is called instead of the class internal variable or method. The self always points to the current object.
self Usage for __init__() Method
One of the most popular uses for the self keyword is using it in the __init__() constructor method. In order to access instance variables and methods, the self keyword is provided to the __init__() method as the first parameter.
class Person(): name="" def __init__(self,name): self.name=name p = Person("İsmail Baydan") print(p.name)
self Usage In Class Method
Another popular use case for the self keyword is using it to access an object or instance methods or variables inside a method. In the following example, we update the name variable when the
set_name() method is called.
class Person(): name="İsmail Baydan" def set_name(self,name): self.name=name p = Person() print(p.name) p.set_name("Ahmet Ali Baydan") print(p.name)
İsmail Baydan Ahmet Ali Baydan