Jul-13-2020, 07:36 AM
If you write a class, then do it right.
You're able to change the behavior of classes.
For example, you can add a method for add and subtract.
With your provided example:
If you have a regular method, then you have to instantiate the class to access the method.
A staticmethod does not supply the function with a reference to self nor to class.
To use this method, the class must be instantiated.
Finally, the classmethod allows calling methods directly on a class without creating an instance.
You're able to change the behavior of classes.
For example, you can add a method for add and subtract.
With your provided example:
class MyValue: def __init__(self, value): self.value = value def __add__(self, other): '''I am method in class Mathematics and not a function''' return self.value + other.value def __sub__(self, other): return self.value - other.value my_val1 = MyValue(5) my_val2 = MyValue(4) print(my_val1 + my_val2)
Output:9
And if you want to have functions, which takes left and right operand and doing something with it, then just use regular functions.def add(a, b): return a + b def sub(a, b): return a - b # or use operator add and sub from operator module: from operator import add, sub print(add(1,2)) print(add(2,3))
Output:from operator import add, sub
print(add(1,2))
print(add(2,3))
I guess you wanted the class, to stick the methods together.If you have a regular method, then you have to instantiate the class to access the method.
A staticmethod does not supply the function with a reference to self nor to class.
To use this method, the class must be instantiated.
Finally, the classmethod allows calling methods directly on a class without creating an instance.
class Math: @classmethod def add(cls, a, b): return a + b @classmethod def sub(cls, a, b): return a - b # calling the method on the class directly print(Math.sub(1,2))
Output:-1
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!