Python Class Variables

It is possible to pass the members of a (i.e. attributes and methods) of a python class to another python class, lets explore how to pass those attributes or methods to another python class

let's create an instance of Emp class as:

e = Emp()

Then pass this instance 'e' to a method of other class, as:

Myclass.mymethod(e)

Here, Myclass is the other class and mymethod() is a static method that belongs to Myclass. In Myclass, the method mymethod() will be declared as a static method as it acts neither on the class variables nor instance variables of Myclass. The purpose of mymethod() is to change the attribute of Emp class.

CopiedCopy Code

def mymethod(e): 
   #increment salary in e by 1000 
   e.salary+=1000; 
   #modify attribute of Emp class 
   e.display() #call the method of Emp class

Class Variables Examples

Example 1:
CopiedCopy Code

#this class contains employee details 
class Emp: #this is a constructor. 
   def __init__(self, id, name, salary): 
      self.id = id 
      self.name = name 
      self.salary = salary 
#this is an instance method. 
   def display(self): 
      print('Id=', self.id) 
      print('Name=', self.name) 
      print('Salary=', self.salary) 
#this class displays employee details 
class Myclass: 
   #method to receive Emp class instance #and display employee details 
   @staticmethod 
   def mymethod(e): #increment salary of e by 1000 
      e.salary+=1000; 
      e.display() #create Emp class instance e 
e = Emp(10, 'Raj kumar', 15000.75) #call static method of Myclass and pass e 
Myclass.mymethod(e)

Let's understand that static methods are used when the class variables or instance variables are not disturbed. We have to use a static method when we want to pass some values from outside and perform some calculation in the method. Here, we are not touching the class variable or instance variables. Following program shows a static method that calculates the value of a number raised to a power.

Example 2:
CopiedCopy Code

#another example for static method 
class Myclass:
  @staticmethod 
  def mymethod(x, n): 
     result = x**n 
     print('{} to the power of {} is {}'.format(x, n, result))
Myclass.mymethod(5, 3) 
Myclass.mymethod(5, 4)