假设以下类定义:
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
a = A()
所以f是常规方法,g是静态方法。
现在,我如何检查函数对象a.f和a.g是否是静态的? Python中有“静态”函数吗?
我必须知道这一点,因为我有包含许多不同函数(方法)对象的列表,并且要调用它们我必须知道它们是否期望“自我”作为参数。
我碰巧有一个模块来解决这个问题。它是Python2 / 3兼容的解决方案。它允许使用从父类继承的方法进行测试。
另外,这个模块还可以测试:
例如:
class Base(object):
attribute = "attribute"
@property
def property_method(self):
return "property_method"
def regular_method(self):
return "regular_method"
@staticmethod
def static_method():
return "static_method"
@classmethod
def class_method(cls):
return "class_method"
class MyClass(Base):
pass
这是staticmethod的解决方案。但我建议使用模块posted here。
import inspect
def is_static_method(klass, attr, value=None):
"""Test if a value of a class is static method.
example::
class MyClass(object):
@staticmethod
def method():
...
:param klass: the class
:param attr: attribute name
:param value: attribute value
"""
if value is None:
value = getattr(klass, attr)
assert getattr(klass, attr) == value
for cls in inspect.getmro(klass):
if inspect.isroutine(value):
if attr in cls.__dict__:
bound_value = cls.__dict__[attr]
if isinstance(bound_value, staticmethod):
return True
return False
让我们试验一下:
>>> 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
所以看起来你可以使用types.FunctionType
来区分静态方法。
你的方法对我来说似乎有点瑕疵,但你可以检查类属性:
(在Python 2.7中):
>>> type(A.f)
<type 'instancemethod'>
>>> type(A.g)
<type 'function'>
或Python 3.x中的实例属性
>>> a = A()
>>> type(a.f)
<type 'method'>
>>> type(a.g)
<type 'function'>
何必?你可以像打电话给f打电话给g:
a = A()
a.f()
a.g()