Do we really need @staticmethod decorator in python to declare static method
I am curious about why we need @staticmethod
decorator to declare method as static
, actually I was reading about static method in python, and I came to know that static method can be callable without instantiating class. So I tried two examples below, but both does same. so why we need @Staticmethoad
?
class StatMethoad():
def stat():
print("without Decorator")
class StatMethaod_with_decorator():
@staticmethod
def stat():
print("With Decorator")
If I call stat
method on class directly both print/shows below values.
StatMethoad.stat()
>>without Decorator
StatMethaod_with_decorator.stat()
>> With Decorator
You need the decorator if you intend to try to call the @staticmethod
from the instance of the class instead of of the class directly
class Foo():
def bar(x):
return x + 5
>>> f = Foo()
>>> f.bar(4)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
f.bar(4)
TypeError: bar() takes 1 positional argument but 2 were given
Now if I declare @staticmethod
the self
argument isn't passed implicitly as the first argument
class Foo():
@staticmethod
def bar(x):
return x + 5
>>> f = Foo()
>>> f.bar(4)
9
The documentation describes some transformations that are done when calling a user defined method:
Note that the transformation from function object to (unbound or bound) method object happens each time the attribute is retrieved from the class or instance. In some cases, a fruitful optimization is to assign the attribute to a local variable and call that local variable. Also notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation. It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class.
For methods marked as staticmethod this is different:
Static method objects provide a way of defeating the transformation of function objects to method objects described above. A static method object is a wrapper around any other object, usually a user-defined method object. When a static method object is retrieved from a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation. Static method objects are not themselves callable, although the objects they wrap usually are. Static method objects are created by the built-in staticmethod() constructor.
if function has some parameters, then call non static method would be failed
and static method didn't use the local variables in the class, but the class method will be
链接地址: http://www.djcxy.com/p/9194.html上一篇: 何时使用接口或抽象类? 何时使用两者?