Object Oriented Programming/Static vs Dynamic
Static vs Dynamic[edit | edit source]
In Object-Oriented-Programming languages, exists static and dynamic methods as well as properties. Here are the key differences.
Static[edit | edit source]
- Cannot access dynamic methods of its own or other class's
- Cannot access dynamic properties of its own or of another class's
- Are only instantiated once since they are static and separate instances will always be identical
Dynamic[edit | edit source]
- Can access dynamic methods of its own or other class's
- Can access dynamic properties of its own or of another class's
- Can be instantiated multiple times, each time with its own unique instance working with potentially unique data
Example[edit | edit source]
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() does 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 its class's properties or methods, it just does the calculation. Since it doesn't need to access unique data of its class, it is only loaded once as any other instance would be identical and a waste of memory, making this a static method.