Python Default Argument is Self Why do We Need it

Here is the reason to supply self-argument in the Python class methods. A python class can have members (functions). Below, you will find an example of class and the importance of self-argument.


Here is useful reason to pass self object in python class function. These are helpful for your project and interviews.


Structure of a class

class <name of the class>:
def <function name>(<arguments>):
...
<members>

The default argument is self. The self-argument states the function belongs to the class that we refer to here. Access to class members' details of one member to another is possible through self-argument. So self-argument is mandatory.

Self Argument

A python class can contain methods. The methods are also called functions.  And the default self-argument you need to supply in all the class methods .

Python class with self argument

class employee: 
    def getdata(self): 
         self.name=input('Enter name\t:') 
         self.age=input('Enter age\t:') 
   def putdata(self): 
         print('Name\t:',self.name)
         print('Age\t:',self.age) 

e1=employee() 
e1.getdata() 
e1.putdata()


Python class same code

Output from python class

Here, I have Imported my .py  module to the Python3 shell. It ran automatically. You may get syntax errors while importing, those you need to fix if any.


Here is list of commands to run Python class


References

Post a Comment

Thanks for your message. We will get back you.

Previous Post Next Post