Static Methods and Class Methods
  • Instance Methods: The most common method type. Able to access data and properties unique to each instance.
  • Static Methods: Cannot access anything else in the class. Totally self-contained code.
  • Class Methods: Can access limited methods in the class. Can modify class specific details.
  • class Vehicle(object):
        """Document String: Define a Vehicle class"""
     
        count = 0; # static variable
    
        def info():
            return Vehicle.count;
    
        info = staticmethod(info) # static function
    
        def __init__(self, brand, year):
            self._brand = brand;
    	self._year = year;
            Vehicle.count += 1;
     
        def __str__(self):
            return self._brand+' '+str(self._year)
    
        def __del__(self):
            Vehicle.count -= 1;
    
    def main():
        vehicles = [Vehicle("Buick", 1998), Vehicle("Lincoln", 1999)]
    
        print(Vehicle.info())
        print(vehicles[1].info())
    
    if __name__ == '__main__':
        main()
    		
    class Vehicle(object):
        """Document String: Define a Vehicle class"""
     
        count = 0;
    
        @staticmethod
        def info():
            return Vehicle.count;
    
        @classmethod
        def cla(cls):
            print('Call class method ...')
            print(Vehicle.info()) # class methods can call static methods
    
        def __init__(self, brand, year):
            self._brand = brand;
    	self._year = year;
            Vehicle.count += 1;
     
        def __str__(self):
            return self._brand+' '+str(self._year)
    
        def __del__(self):
            Vehicle.count -= 1;
    
    def main():
        vehicles = [Vehicle("Buick", 1998), Vehicle("Lincoln", 1999)]
    
        print(Vehicle.info()) # call static method
        print(vehicles[1].info())
    
        Vehicle.cla() # call class method
    
    if __name__ == '__main__':
        main()
    		
    Reference
  • Instance vs. Static vs. Class Methods in Python: The Important Differences