Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: check if method is static

assume following class definition:

class A:
  def f(self):
    return 'this is f'

  @staticmethod
  def g():
    return 'this is g'

a = A() 

So f is a normal method and g is a static method.

Now, how can I check if the funcion objects a.f and a.g are static or not? Is there a "isstatic" funcion in Python?

I have to know this because I have lists containing many different function (method) objects, and to call them I have to know if they are expecting "self" as a parameter or not.

like image 835
proggy Avatar asked Jan 04 '12 12:01

proggy


People also ask

How do you know if a method should be static?

You should consider making a method static in Java : 1) If a method doesn't modify the state of the object, or not using any instance variables. 2) You want to call the method without creating an instance of that class.

What does @staticmethod do in Python?

The @staticmethod is a built-in decorator that defines a static method in the class in Python. A static method doesn't receive any reference argument whether it is called by an instance of a class or by the class itself.

What is the difference between Classmethod and Staticmethod in Python?

Class method can access and modify the class state. Static Method cannot access or modify the class state. The class method takes the class as parameter to know about the state of that class. Static methods do not know about class state.


1 Answers

Lets experiment a bit:

>>> import types
>>> class A:
...   def f(self):
...     return 'this is f'
...   @staticmethod
...   def g():
...     return 'this is g'
...
>>> a = A()
>>> a.f
<bound method A.f of <__main__.A instance at 0x800f21320>>
>>> a.g
<function g at 0x800eb28c0>
>>> isinstance(a.g, types.FunctionType)
True
>>> isinstance(a.f, types.FunctionType)
False

So it looks like you can use types.FunctionType to distinguish static methods.

like image 51
Roman Bodnarchuk Avatar answered Oct 06 '22 01:10

Roman Bodnarchuk