Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad form to call a classmethod as a method from an instance?

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.

?

like image 461
Josh Gibson Avatar asked Mar 28 '09 02:03

Josh Gibson


People also ask

Can you call a @classmethod on an instance?

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.

When should you use a Classmethod Python?

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.

Can I call method from Init Python?

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.

What is the difference between Classmethod and Staticmethod?

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.


2 Answers

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) 
like image 164
Toni Ruža Avatar answered Sep 21 '22 10:09

Toni Ruža


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.

like image 43
Matt Good Avatar answered Sep 23 '22 10:09

Matt Good