Ex.
If I have something like this:
class C(object):
@classmethod
def f(cls, x):
return x + x
This will work:
c = C()
c.f(2)
4
But is that bad form? Should I only call
C.f()
or
c.__class__.f()
Obviously, this would only make sense in cases where f doesn't interact with self/cls expecting it to be class.
?
A class method is a method that's shared among all objects. To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself.
You can use class methods for any methods that are not bound to a specific instance but the class. In practice, you often use class methods for methods that create an instance of the class. When a method creates an instance of the class and returns it, the method is called a factory method.
You cannot call them explicitly. For instance, when you create a new object, Python automatically calls the __new__ method, which in turn calls the __init__ method.
The class method takes cls (class) as first argument. The static method does not take any specific parameter. Class method can access and modify the class state. Static Method cannot access or modify the class state.
If you are tempted to call a class method from an instance you probably don't need a class method.
In the example you gave a static method would be more appropriate precisely because of your last remark (no self/cls interaction).
class C(object): @staticmethod def f(x): return x + x
this way it's "good form" to do both
c = C() c.f(2)
and
C.f(2)
I don't recall using a classmethod like this from outside the class, but it is certainly ok for an instance method to call a classmethod on itself (e.g. self.foo()
where foo
is a classmethod). This makes sure that inheritance acts as expected, and will call .foo()
in the right subclass instead of the base class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With