Class based functions include a reference to self so that you can know which class instance called it. It represents the instance of the class. It is not a keyword in python. We can access attributes and methods of class by using self. It attaches the attributes with the given arguments.
class name(): def __init__(self,ob1,ob2): self.ob1=ob1 self.ob2=ob2 def show(self): print(“ob1 is”, self.ob1) print(“ob2 is”, self.ob2)
Python class self constructor- Self is used to refer to a variable field within the class.
class girl: def __init__(self, mary): self.name=mary def get_girl_name(self): return self.name
Important points to know about “self”:-
- Self is not a keyword in python. In place of self we can use other words also. But it is good to use self as it increases the readability of the program.
- Self makes it easy to differentiate between instance attributes and local variables. Python has no explicit variable declaration.
- Self is the first parameter of methods that represents the instance of the class in python.