Featured

    Featured Posts

Python OOPS Tutorial 5:Self-variable In Python


Self-variable In Python:



 v  self is the default variable which is always pointing to current object (like this
         keyword in Java)

Usage of self-variable

 §  self variable can be used to refer current class instance variable.

 §  By using self we can access instance variables and instance methods of object.
    
             In Python constructor must be contains first parameter as self.
                     def __init__(self):

 In Python method must be contains first parameter as self.
                       def fun(self):

 §  Every method, included in the class definition passes the object in question as its first 
       parameter. The word self is used for this parameter (usage of self is actually by  
       convention, as the word self has no inherent.

Purpose Of self Variable
        self . (self dot)
§   which can be used to differentiate variable of class and formal parameters of method 
   or constructor.

  "self" variable are used for two purpose, they are
§   It always points to current class object.     

 §  Whenever the formal parameter and data member of the class are similar and PVM 
       gets an ambiguity (no clarity between formal parameter and data members of the 
       class).

To differentiate between formal parameter and data member of the class, the data members of the class must be preceded by "self".

  Syntax-:

self.data member of current class.

class Employee:
    def __init__(self,id,name):
        self.id=id
        self.name=name
   
    def display(self):
        print(self.id)
        print(self.name)

e=Employee(101,'Scott')
e.display()




author

Author Name

Author Description!

Get Free Email Updates to your Inbox!

Post a Comment

www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews