What is the purpose of self in Python?
The self represents the instance of the class. This keyword helps in accessing the attributes and methods of the class and binds the attributes with the given arguments.
The purpose of using self is that Python does not use the ‘@’ syntax to refer to instance attributes. In Python methods do in a way that makes the instance to be passed automatically, but not received automatically.
Example:
class laptop(): # init method or constructor def __init__(self, model, color): self.model = model self.color = color def show(self): print("Model is", self.model ) print("color is", self.color ) # both objects have different self which # contain their attributes lenovo = laptop("lenovo", "blue") hp = laptop("hp", "black") lenovo.show() hp.show()
Output:
Model is lenovo color is blue Model is hp color is black
Self is a not a real python keyword
self is parameter in function and user can use different parameter name in place of it.But using self is advisable as it increases the readability of code.
Example:
class this_is_class: def show(in_place_of_self): print("we can use different " "parameter name in place of self") obj = this_is_class() obj.show()
Output:
we can use different parameter name in place of self
Share: