programing

Python에서 현재 모듈 내의 모든 클래스 목록을 얻으려면 어떻게 해야 합니까?

procenter 2022. 9. 21. 22:32
반응형

Python에서 현재 모듈 내의 모든 클래스 목록을 얻으려면 어떻게 해야 합니까?

저는 보통 다음과 같은 모듈에서 모든 클래스를 추출하는 예를 많이 봐왔습니다.

# foo.py
class Foo:
    pass

# test.py
import inspect
import foo

for name, obj in inspect.getmembers(foo):
    if inspect.isclass(obj):
        print obj

신난다.

하지만 현재 모듈의 모든 수업을 어떻게 받을 수 있는지 알 수 없습니다.

# 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()술어를 사용합니다.

어때

g = globals().copy()
for name, obj in g.iteritems():

?

방향으로 있습니다. '어느 정도'나 '어느 정도'나 '어느 정도'나 '어느 정도'나 '어느 정도'나 '어느 정도'나 '어느 정도'를 붙이면 .import foopy 에 해, foo 를 합니다.파이로 하다inspect.getmembers(foo)정상적으로 동작합니다.

빌트인 플러스에서 필요한 모든 것을 얻을 수 있었습니다.

# 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 pyclbr
print(pyclbr.readmodule(__name__).keys())

소스 사용하기 Python이 지원하는 합니다..pyfilename을 클릭합니다.

현재 모듈에 속하는 모든 클래스를 가질 경우 다음을 사용할 수 있습니다.

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의 답변을 사용하여 모듈의 다른 클래스를 Import하고 있는 경우 해당 클래스도 Import됩니다.

★★★★★★★★★★★★★★★★★★★★.member.__module__ == __name__에서 사용되는 술어에 추가되고 있습니다.is_class_member이 문은 클래스가 모듈에 실제로 속해 있는지 확인합니다.

술어는 부울값을 반환하는 함수(콜 가능)입니다.

현재 모듈에 정의된 모든 클래스를 가져오기 위해 사용하는 행입니다(가져오지 않음).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__]

이것은 내 경험상 더 유용하다.

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()

나는 네가 이런 일을 할 수 있다고 생각해.

class custom(object):
    __custom__ = True
class Alpha(custom):
    something = 3
def GetClasses():
    return [x for x in globals() if hasattr(globals()[str(x)], '__custom__')]
print(GetClasses())`

만약 당신이 개인 수업이 필요하다면

저는 종종 첫 번째 인수가 많은 다른 클래스 중 하나를 참조하는 명령줄 유틸리티를 쓰고 있습니다.를 들어, 「」입니다../something.py feature command —-arguments서, snowledge.Feature 입니다.command을 사용하다이 작업을 쉽게 하는 기본 클래스가 있습니다.

이 기본 클래스는 모든 하위 클래스와 함께 디렉토리에 있는 것으로 가정합니다. 다음 '아까보다'로 전화를 됩니다.ArgBaseClass(foo = bar).load_subclasses()사전이 반환됩니다.예를 들어 디렉토리가 다음과 같은 경우:

  • arg_base_class.화이
  • 특징.화이

가정하다feature.py용구class Feature(ArgBaseClass)그 후, 상기의 기동load_subclasses돌아온다{ 'feature' : <Feature object> }동일.kwargs(foo = bar)가 에 전달됩니다.Feature학급.

#!/usr/bin/env python3
import os, pkgutil, importlib, inspect

class ArgBaseClass():
    # Assign all keyword arguments as properties on self, and keep the kwargs for later.
    def __init__(self, **kwargs):
        self._kwargs = kwargs
        for (k, v) in kwargs.items():
            setattr(self, k, v)
        ms = inspect.getmembers(self, predicate=inspect.ismethod)
        self.methods = dict([(n, m) for (n, m) in ms if not n.startswith('_')])

    # Add the names of the methods to a parser object.
    def _parse_arguments(self, parser):
        parser.add_argument('method', choices=list(self.methods))
        return parser

    # Instantiate one of each of the subclasses of this class.
    def load_subclasses(self):
        module_dir = os.path.dirname(__file__)
        module_name = os.path.basename(os.path.normpath(module_dir))
        parent_class = self.__class__
        modules = {}
        # Load all the modules it the package:
        for (module_loader, name, ispkg) in pkgutil.iter_modules([module_dir]):
            modules[name] = importlib.import_module('.' + name, module_name)

        # Instantiate one of each class, passing the keyword arguments.
        ret = {}
        for cls in parent_class.__subclasses__():
            path = cls.__module__.split('.')
            ret[path[-1]] = cls(**self._kwargs)
        return ret
import Foo 
dir(Foo)

import collections
dir(collections)

파일 맨 위에 다음 항목을 배치할 수 있습니다.

def get_classes():
    import inspect, sys
    return dict(inspect.getmembers(
        sys.modules[__name__],
        lambda member: inspect.isclass(member) and member.__module__ == __name__
    ))

이 로직은 함수 정의로 정리되어 있기 때문에 모듈의 맨 위에 배치할 수 있습니다.사전을 최상위 개체로 사용하려면 파일 하단에 정의를 배치하여 모든 클래스가 포함되도록 해야 합니다.

Python Interpreter로 이동합니다.help('module_name')입력하고 Enter 키를 누릅니다(예: help('os')).여기에서는, 다음의 출력의 일부를 붙여 넣었습니다.

class statvfs_result(__builtin__.object)
     |  statvfs_result: Result from statvfs or fstatvfs.
     |
     |  This object may be accessed either as a tuple of
     |    (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),
     |  or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.
     |
     |  See os.statvfs for more information.
     |
     |  Methods defined here:
     |
     |  __add__(...)
     |      x.__add__(y) <==> x+y
     |
     |  __contains__(...)
     |      x.__contains__(y) <==> y in x

언급URL : https://stackoverflow.com/questions/1796180/how-can-i-get-a-list-of-all-classes-within-current-module-in-python

반응형