質問

変数がインスタンスメソッドであるかどうかを確認するにはどうすればよいですか? Python 2.5を使用しています。

このようなもの:

class Test:
    def method(self):
        pass

assert is_instance_method(Test().method)
役に立ちましたか?

解決

inspect.ismethod あなたが呼ぶことができるものではなく、間違いなく方法を持っているかどうかを知りたいことです。

import inspect

def foo(): pass

class Test(object):
    def method(self): pass

print inspect.ismethod(foo) # False
print inspect.ismethod(Test) # False
print inspect.ismethod(Test.method) # True
print inspect.ismethod(Test().method) # True

print callable(foo) # True
print callable(Test) # True
print callable(Test.method) # True
print callable(Test().method) # True

callable 引数がメソッドである場合、引数が機能、関数( lambdas)、インスタンス __call__ またはクラス。

メソッドは、関数とは異なる特性を持っています( im_classim_self)。あなたが望んでいるのは

assert inspect.ismethod(Test().method)  

他のヒント

それが正確にインスタンスメソッドであるかどうかを知りたい場合は、次の関数を使用します。 (メタクラスで定義され、クラスクラスのメソッドでアクセスされるメソッドを考慮しますが、インスタンスメソッドとも見なすこともできます)

import types
def is_instance_method(obj):
    """Checks if an object is a bound method on an instance."""
    if not isinstance(obj, types.MethodType):
        return False # Not a method
    if obj.im_self is None:
        return False # Method is not bound
    if issubclass(obj.im_class, type) or obj.im_class is types.ClassType:
        return False # Method is a classmethod
    return True

通常、それをチェックするのは悪い考えです。何でも使用できる方が柔軟です callable() メソッドと交換可能です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top