Instance Variable in Python

 


Python Class Instance Variable

  • Variables defined inside a Class Method with "self" as a keyword.
Example :


#program to define instance variable

class Team :
team_name =
"INDIA"                #static Variable

def assign_team_member(self):
self.cricket_team = 11         # instance variable, defined with keyword self
self.kabaddi_team = 7          # instance variable, defined with keyword self



  • They get memory at object creation time, not at class loading time. so without creating object, instance variables can not be called.
Example : 


#program

class Team :
team_name =
"INDIA"

def assign_team_member(self):
self.cricket_team = 11
self.kabaddi_team = 7

def display_team_member(self,):
print("\nno of players in cricket team :", self.cricket_team)
print("\nno of players in kabaddi team :", self.kabaddi_team)

print("Team_name : ", Team.team_name) # calling static variable with class name
print("assigning value", Team.assign_team_member()) # calling method without creating object

 #Output

Team_name : INDIA
Traceback (most recent call last):
File "
C:/Self_Practice_Er_M_S_Dandyan/Python/Pycharm/xml/main.py", line 15, in <module>
print("assigning value", Team.assign_team_member())
TypeError: assign_team_member() missing 1 required positional argument: 'self'



  • To call instance variable, we use Object.
Example : 

 #program

class Team :
team_name =
"INDIA"                    # static Variable, will load at class loading time

def assign_team_member(self):
self.cricket_team = 11             # Instance variable, will load at object creation time
self.kabaddi_team = 7              # Instance variable

def display_team_member(self,):
print("\nno of players in cricket team :", self.cricket_team)
print("\nno of players in kabaddi team :", self.kabaddi_team)

print("Team_name ; ", Team.team_name)

team_details = Team()
team_details.assign_team_member()
team_details.display_team_member()

 #output

Team_name ; INDIA

no of players
in cricket team : 11

no of players in kabaddi team : 7


  • They hold unique value for individual Object
Example :

 #program

class Employee_data :
company_name =
"AETies"

def assign_employee_data(self, name, id, salary):
self.emp_name = name
self.emp_id = id
self.emp_salary = salary

def display_employee_data(self,):
print("\nname :", self.emp_name, end="\t")
print("id :", self.emp_id, end="\t")
print("salary :", self.emp_salary, end="\t")
print("Company : ", Employee_data.company_name)

emp_1 = Employee_data()
emp_2 = Employee_data()

emp_1.assign_employee_data(
"Techno Xpresss", 101, 25.876)
emp_2.assign_employee_data(
"Er M S Dandyan", 102, 28.786)

emp_1.display_employee_data()
emp_2.display_employee_data()

 #Output

name : Techno Xpresss id : 101 salary : 25.876 Company : AETies

name : Er M S Dandyan id :
102 salary : 28.786 Company : AETies





Comments

My photo
Techno Xpresss
Bangalore, Karnataka, India