Object Oriented Programming/Static vs Dynamic

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Static vs Dynamic[edit]

In Object-Oriented-Programming languages, there exist static and dynamic methods as well as properies. Here are the key differences.

Static[edit]

  • Cannot access dynamic methods of it's own or other class's
  • Cannot access dynamic properties of it's own or of another class's
  • Are only instantiated once since they are static and separate instances will always be identical

Dynamic[edit]

  • Can access dynamic methods of it's own or other class's
  • Can access dynamic properties of it's own or of another class's
  • Can be instantiated multiple times, each time with it's own unique instance working with potentially unique data

Example[edit]

class Values():

  def __init__(self, value):
    self.value = value

  def squared(self, value):
    self.value = self.multiply_value(value, value)

  @staticmethod
  def multiply_value(value1, value2):
    return value1 * value2

In the code above, you can see that the method squared() takes self as a parameter. This allows it to access other properties and methods of the class. As you can see, it takes an initial passed in value, does some modification to it, and then sets the class's value property to the result of the calculation. Since it can access other class methods/properties and modify the class's state, it is considered a dynamic method.

On the other hand, you can see that multiply_value() dose NOT have self as a parameter. All that this method does is multiply the two passed in values together and return the result. It never has or requires access to it's class's properties or methods, it just does the calculation. Since it doesn't need to access unique data of it's class, it is only loaded once as any other instance would be identical and a waste of memory, making this a static method.

See Also[edit]

Wikipedia:Method(computer programming)


Python Programming/Classes