モジュールからすべてのクラスを抽出する例はよく見かけますが、通常は次のようなものです:
# foo.py
class Foo:
pass
# test.py
import inspect
import foo
for name, obj in inspect.getmembers(foo):
if inspect.isclass(obj):
print obj
すごいなー。
しかし、_current_moduleから全てのクラスを取得する方法がわかりません'。
# foo.py
import inspect
class Foo:
pass
def print_classes():
for name, obj in inspect.getmembers(???): # what do I do here?
if inspect.isclass(obj):
print obj
# test.py
import foo
foo.print_classes()
これはおそらく本当に当たり前のことだと思うのですが、何も見つけることができません。どなたか教えてください。
これを試してみてください:
import sys
current_module = sys.modules[__name__]
あなたの文脈では:
import sys, inspect
def print_classes():
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isclass(obj):
print(obj)
さらに、さらに、さらに:
clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
inspect.getmembers()`は述語を取るからです。
dir
に加えて[getattr
](https:// docs.python.org/2/library/functions.html#getattr)。
# Works on pretty much everything, but be mindful that
# you get lists of strings back
print dir(myproject)
print dir(myproject.mymodule)
print dir(myproject.mymodule.myfile)
print dir(myproject.mymodule.myfile.myclass)
# But, the string names can be resolved with getattr, (as seen below)
しかし、それは毛玉のように見えます:
def list_supported_platforms():
"""
List supported platforms (to match sys.platform)
@Retirms:
list str: platform names
"""
return list(itertools.chain(
*list(
# Get the class's constant
getattr(
# Get the module's first class, which we wrote
getattr(
# Get the module
getattr(platforms, item),
dir(
getattr(platforms, item)
)[0]
),
'SYS_PLATFORMS'
)
# For each include in platforms/__init__.py
for item in dir(platforms)
# Ignore magic, ourselves (index.py) and a base class.
if not item.startswith('__') and item not in ['index', 'base']
)
))
現在のモジュールに属するすべてのクラスを使用する場合は、これを使用できます。
import sys, inspect
def print_classes():
is_class_member = lambda member: inspect.isclass(member) and member.__module__ == __name__
clsmembers = inspect.getmembers(sys.modules[__name__], is_class_member)
Nadiaの回答を使用してモジュールに他のクラスをインポートしている場合、そのクラスもインポートされます。
そのため、「member.module == name」が「is_class_member」で使用される述語に追加されます。 このステートメントは、クラスが実際にモジュールに属していることを確認します。
述語は、ブール値を返す関数(呼び出し可能)です。
Python 2および3で機能する別のソリューション:
#foo.py
import sys
class Foo(object):
pass
def print_classes():
current_module = sys.modules[__name__]
for key in dir(current_module):
if isinstance( getattr(current_module, key), type ):
print(key)
# test.py
import foo
foo.print_classes()
これは、現在のモジュールで定義されているすべてのクラスを取得するために使用する行です(つまり、インポートされていません)。 PEP-8によると少し長いですが、必要に応じて変更できます。
import sys
import inspect
classes = [name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if obj.__module__ is __name__]
これにより、クラス名のリストが表示されます。 クラスオブジェクト自体が必要な場合は、代わりにobjを保持してください。
classes = [obj for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if obj.__module__ is __name__]
これは私の経験でより役に立ちました。