Python: check if method is static

前端 未结 5 1138
梦谈多话
梦谈多话 2020-12-06 16:48

assume following class definition:

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

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

a = A() 

5条回答
  •  无人及你
    2020-12-06 16:56

    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
    >
    >>> a.g
    
    >>> 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.

提交回复
热议问题