[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Reasoning of calling a method on class object instead of class instance object

Arup Rakshit <ar at zeit.io> writes:

> class RefrigeratedShippingContainer(ShippingContainer):
>     # ...
>     @staticmethod
>     def _c_to_f(celsius):
>         return celsius * 9/5 + 32
>     @staticmethod
>     def _f_to_c(fahrenheit):
>         return (fahrenheit - 32) * 5/9

Both those functions are decorated with ?staticmethod?. That means
that the function will, unlike typical methods, not automatically
receive any implicit first argument. That's why the function signature
has no ?self? or ?klass? or the like.

> If I call `_c_to_f`, `_f_to_c` methods on `self` instead of
> `RefrigeratedShippingContainer` class object, still it works.

That's right, and is indeed the point of making a static method on a
class. From the above documentation link:

    [A staticmethod-decorated function] can be called either on the
    class (such as `C.f()`) or on an instance (such as `C().f()`). The
    instance is ignored except for its class.

> So what is the reason behind of this calling on the class object,
> instead class instance object?

Whichever makes the most sense in the code where that function is

The purpose of a static method is to imply that, though the function
*could* be entirely separate from any class, it is conceptually part of
a spacific class's behaviour.

In the specific example you show, I expect the code maintenance was
deemed to be easier when the RefrigeratedShippingContainer encapsulates
the conversions of temperature units.

 \         ?When we pray to God we must be seeking nothing ? nothing.? |
  `\                                                ?Francis of Assisi |
_o__)                                                                  |
Ben Finney