In this article I will explain How to Create Instance Variables and Class Variables in Python. Apart from class variables, and instance variables, we can also define variables within a method. In such a case, these variables are local variables and can be used within that method only.
Further, we access the instance variables using the object name. Whereas, the class variables are accesses using the class name. Moreover, the value of class variables remain same for each object. While, the instance variables take different values for different objects.
The following example shows the usage of instance variables and class variables. As can be seen, the variables a and b are class variables. Therefore, the values of these two variables remain same for all objects of the class. In contrast, the variables x and y are instance variables. Hence, these variables take different values for each object of the class. Also, we pass the values of instance variables as parameters to the constructor while creating the objects. Further, we can access the instance variables using the self keyword. While, we access the class variables usinf=g the name of the class. The following example also shows that how to access and use both instance variables and class variables in an expression. The show() method defined in the class computes and displays the sum of these four variables.
class MyClass: a=100 b=200 def __init__(self, x, y): self.x=x self.y=y def show(self): print("a = ", MyClass.a) print("b = ", MyClass.b) print("x = ", self.x) print("y = ", self.y) print("sum = ", MyClass.a+MyClass.b+self.x+self.y) ob1=MyClass(670, 433) ob1.show() ob2=MyClass(56, 24) ob2.show() ob3=MyClass(6, 3) ob3.show()
Using Class Variables and Instance Variables in EmployeePay Class
Another example is shown here. Basically, the EmployeePay class contains three class variables. These variables are hra, da, and deductions. So, each object of this class uses the same values for these variables. However, the class has two instance variables. These re ename, and basic representing employee name, and basic salary. Also, the class has a method showNetPay(). The method computes the net pay of an employee. Further, it contains an expression involving the use of both types of variables. The following section shows the complete code. Also, note the use of self keyword.
class EmployeePay: hra=0.23 da=0.5 deductions=5000 def __init__(self, ename, basic): self.ename=ename self.basic=basic def showNetPay(self): net=EmployeePay.hra*self.basic+EmployeePay.da*self.basic-EmployeePay.deductions+self.basic print("Employee Name: ", self.ename) print("Basic Salary: ", self.basic) print("Net Salary: ", net) print("First Object...") ob1=EmployeePay("Pratham", 10000) ob1.showNetPay() print("Second Object...") ob2=EmployeePay("Aditya", 14000) ob2.showNetPay() print("Third Object...") ob3=EmployeePay("Ankur", 21000) ob3.showNetPay()
Comparing Rows of Two Tables with ADO.NET