別の関数をパラメーターとして受け取る関数があります。関数がクラスのメンバーである場合、そのクラスの名前を見つける必要があります。例えば
def analyser(testFunc):
print testFunc.__name__, 'belongs to the class, ...
と思いました
testFunc.__class__
私の問題は解決しますが、それは testFunc が関数であることを示しています。
別の関数をパラメーターとして受け取る関数があります。関数がクラスのメンバーである場合、そのクラスの名前を見つける必要があります。例えば
def analyser(testFunc):
print testFunc.__name__, 'belongs to the class, ...
と思いました
testFunc.__class__
私の問題は解決しますが、それは testFunc が関数であることを示しています。
Python 3.3 から.im_class
はなくなりました。代わりに使用できます.__qualname__
。対応する PEP は次のとおりです: https://www.python.org/dev/peps/pep-3155/
class C:
def f(): pass
class D:
def g(): pass
print(C.__qualname__) # 'C'
print(C.f.__qualname__) # 'C.f'
print(C.D.__qualname__) #'C.D'
print(C.D.g.__qualname__) #'C.D.g'
ネストされた関数の場合:
def f():
def g():
pass
return g
f.__qualname__ # 'f'
f().__qualname__ # 'f.<locals>.g'
testFunc.im_class
https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy
im_class
バインドされたメソッドのクラスim_self
、またはバインドされていないメソッドのメソッドを要求したクラスです
私は Python の専門家ではありませんが、これは機能しますか?
testFunc.__self__.__class__
バインドされたメソッドで機能するようですが、あなたの場合、バインドされていないメソッドを使用している可能性があります。
testFunc.__objclass__
使用したテストは次のとおりです。
Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib
>>> hd = hashlib.md5().hexdigest
>>> hd
<built-in method hexdigest of _hashlib.HASH object at 0x7f9492d96960>
>>> hd.__self__.__class__
<type '_hashlib.HASH'>
>>> hd2 = hd.__self__.__class__.hexdigest
>>> hd2
<method 'hexdigest' of '_hashlib.HASH' objects>
>>> hd2.__objclass__
<type '_hashlib.HASH'>
そうそう、別のこと:
>>> hd.im_class
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 'im_class'
>>> hd2.im_class
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'method_descriptor' object has no attribute 'im_class'
したがって、防弾が必要な場合は、それも処理する必要が__objclass__
あり__self__
ます。しかし、走行距離は異なる場合があります。
インスタンスメソッドには属性 .im_class .im_func .im_self があります
http://docs.python.org/library/inspect.html#types-and-members
おそらく、関数がattr .im_classを持っているかどうかを確認し、そこからクラス情報を取得したいと思うでしょう。