programing

Python 클래스의 메서드 목록을 가져오려면 어떻게 해야 합니까?

itsource 2022. 10. 5. 23:37
반응형

Python 클래스의 메서드 목록을 가져오려면 어떻게 해야 합니까?

클래스의 메서드를 반복하거나 존재하는 메서드에 따라 클래스 또는 인스턴스 개체를 다르게 처리합니다.수업 방법 목록을 가져오려면 어떻게 해야 합니까?

다음 항목도 참조해 주세요.

「」의 )optparse.OptionParser★★★★★★★★★★★★★★★★★★:

>>> from optparse import OptionParser
>>> import inspect
#python2
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
 ('add_option', <unbound method OptionParser.add_option>),
 ('add_option_group', <unbound method OptionParser.add_option_group>),
 ('add_options', <unbound method OptionParser.add_options>),
 ('check_values', <unbound method OptionParser.check_values>),
 ('destroy', <unbound method OptionParser.destroy>),
 ('disable_interspersed_args',
  <unbound method OptionParser.disable_interspersed_args>),
 ('enable_interspersed_args',
  <unbound method OptionParser.enable_interspersed_args>),
 ('error', <unbound method OptionParser.error>),
 ('exit', <unbound method OptionParser.exit>),
 ('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
 ...
 ]
# python3
>>> inspect.getmembers(OptionParser, predicate=inspect.isfunction)
...

「 」라는 점에 해 주세요.getmembers2번입니다.첫 번째 항목은 멤버 이름이고 두 번째 항목은 값입니다.

를 들다, 하다, 하다, 하다, 하다, 하다, 할 도 있어요.getmembers:

>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...

게 요.dir(theobject)및write)을및의 경우).

Python에서는 모든 것(필드까지)이 호출될 수 있기 때문에 메서드만 나열하는 내장 함수는 없을 것 같습니다.통과하는 객체가dir 가능 여부입니다.

외부 라이브러리 없이 Python 3.x 응답

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]

dunder-signed 결과:

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]

목록 클래스와 관련된 모든 메서드를 알고 싶다면 다음을 입력하십시오.

 print (dir(list))

위는 목록 클래스의 모든 메서드를 제공합니다.

을 시험해 보십시오.__dict__.

도 있습니다..class.__dict__:

from types import FunctionType

class Foo:
    def bar(self): pass
    def baz(self): pass

def methods(cls):
    return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]

methods(Foo)  # ['bar', 'baz']

다음 코드를 사용하여 python 클래스의 모든 메서드를 나열할 수 있습니다.

dir(className)

그러면 클래스의 모든 메서드 이름 목록이 반환됩니다.

기본 클래스의 메서드를 결과에 상속(오버라이드되지 않음)할지 여부를 고려해야 합니다.dir() ★★★★★★★★★★★★★★★★★」inspect.getmembers()메서드가 만, 「Base Class 메서드」를 는,__dict__아트리뷰트

이 "이고 "일반" 방식이 "일반" 방식입니다.staticmethod,classmethodsyslog.
가 .

for k, v in your_class.__dict__.items():
    if "function" in str(v):
        print(k)

은 '함수 '함수', '함수', '함수', '함수'를 다른 할 수 .if그에 상응하는 조건을 제시합니다.
Python 2.7 Python 3.5 입니다.

해라print(help(ClassName))클래스의 메서드를 출력합니다.

상위 등급의 답변이 명확하지 않기 때문에 그냥 두고 있습니다.

이것은 Enum을 기반으로 한 일반 클래스가 아닌 단순한 테스트입니다.

# -*- coding: utf-8 -*-
import sys, inspect
from enum import Enum

class my_enum(Enum):
    """Enum base class my_enum"""
    M_ONE = -1
    ZERO = 0
    ONE = 1
    TWO = 2
    THREE = 3

    def is_natural(self):
            return (self.value > 0)
    def is_negative(self):
            return (self.value < 0)

def is_clean_name(name):
    return not name.startswith('_') and not name.endswith('_')
def clean_names(lst):
    return [ n for n in lst if is_clean_name(n) ]
def get_items(cls,lst):
    try:
            res = [ getattr(cls,n) for n in lst ]
    except Exception as e:
            res = (Exception, type(e), e)
            pass
    return res


print( sys.version )

dir_res = clean_names( dir(my_enum) )
inspect_res = clean_names( [ x[0] for x in inspect.getmembers(my_enum) ] )
dict_res = clean_names( my_enum.__dict__.keys() )

print( '## names ##' )
print( dir_res )
print( inspect_res )
print( dict_res )

print( '## items ##' )
print( get_items(my_enum,dir_res) )
print( get_items(my_enum,inspect_res) )
print( get_items(my_enum,dict_res) )

그리고 이것은 출력 결과입니다.

3.7.7 (default, Mar 10 2020, 13:18:53) 
[GCC 9.2.1 20200306]
## names ##
['M_ONE', 'ONE', 'THREE', 'TWO', 'ZERO']
['M_ONE', 'ONE', 'THREE', 'TWO', 'ZERO', 'name', 'value']
['is_natural', 'is_negative', 'M_ONE', 'ZERO', 'ONE', 'TWO', 'THREE']
## items ##
[<my_enum.M_ONE: -1>, <my_enum.ONE: 1>, <my_enum.THREE: 3>, <my_enum.TWO: 2>, <my_enum.ZERO: 0>]
(<class 'Exception'>, <class 'AttributeError'>, AttributeError('name'))
[<function my_enum.is_natural at 0xb78a1fa4>, <function my_enum.is_negative at 0xb78ae854>, <my_enum.M_ONE: -1>, <my_enum.ZERO: 0>, <my_enum.ONE: 1>, <my_enum.TWO: 2>, <my_enum.THREE: 3>]

자, 여기 있습니다.

  • dir완전한 데이터를 제공하지 않다
  • inspect.getmembers완전한 데이터를 제공하지 않고 접근할 수 없는 내부 키를 제공합니다.getattr()
  • __dict__.keys()완전하고 신뢰할 수 있는 결과를 제공하다

왜 이렇게 표가 틀렸을까?내가 틀린 곳이 어디니?그리고 대답하는 다른 사람들이 그렇게 낮은 표를 가지고 있는 곳이 어디인가요?

다음과 같은 접근방식이 있습니다.

[getattr(obj, m) for m in dir(obj) if not m.startswith('__')]

클래스 인스턴스를 처리할 때는 이름만 반환하는 것이 아니라 메서드 참조가 포함된 목록을 반환하는 것이 좋습니다.그게 당신의 목표라면

  1. 사용 안 함import
  2. 개인 방법 제외(예:__init__리스트에서 )를 참조해 주세요.

쓸모가 있을지도 모른다.또, 확실히 하는 것이 좋을지도 모릅니다.callable(getattr(obj, m)),부터dir내의 모든 Atribute를 반환합니다.obj방법뿐만이 아닙니다.

한마디로 말하자면

class Ghost:
    def boo(self, who):
        return f'Who you gonna call? {who}'

인스턴스 취득을 확인할 수 있습니다.

>>> g = Ghost()
>>> methods = [getattr(g, m) for m in dir(g) if not m.startswith('__')]
>>> print(methods)
[<bound method Ghost.boo of <__main__.Ghost object at ...>>]

바로 호출할 수 있습니다.

>>> for method in methods:
...     print(method('GHOSTBUSTERS'))
...
Who you gonna call? GHOSTBUSTERS

§ 사용 사례:

이걸 유닛 테스트에 사용했어요.모든 메서드가 동일한 프로세스의 바리에이션을 실행하는 클래스가 있었습니다.그 결과, 테스트 시간이 길어지고, 각 메서드는 다른 메서드에서 약간만 조정되었습니다.DRY는 먼 꿈이었어.

모든 방법에 대해 단일 테스트를 받아야 한다고 생각하여 위와 같은 테스트를 반복했습니다.

그 대신 코드 자체를 DRY에 준거하도록 리팩터링해야 한다는 것을 깨달았지만...이건 미래에도 여전히 아무렇게나 까다로운 영혼에 도움이 될지도 몰라

이것도 동작합니다.

mymodule.py:

def foo(x):
   return 'foo'
def bar():
   return 'bar'

다른 파일:

import inspect
import mymodule
method_list = [ func[0] for func in inspect.getmembers(mymodule, predicate=inspect.isroutine) if callable(getattr(mymodule, func[0])) ]

출력:

['푸', '바']

Python 문서:

inspect.isroutine(object)

개체가 사용자 정의 함수 또는 메서드인 경우 true를 반환합니다.

def find_defining_class(obj, meth_name):
    for ty in type(obj).mro():
        if meth_name in ty.__dict__:
            return ty

그렇게

print find_defining_class(car, 'speedometer') 

Python 페이지 210을 생각해 보세요.

제가 만든 기능을 사용하셔도 됩니다.

def method_finder(classname):

    non_magic_class = []

    class_methods = dir(classname)

    for m in class_methods:

        if m.startswith('__'):

            continue

        else:

            non_magic_class.append(m)

    return non_magic_class




method_finder(list)

출력:

['append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']
methods = [(func, getattr(o, func)) for func in dir(o) if callable(getattr(o, func))]

과 같은 리스트를 제공하다

methods = inspect.getmembers(o, predicate=inspect.ismethod)

한다.

오래된 투고인 것은 알지만, 이 기능을 작성했을 뿐입니다.누군가가 답을 찾기 위해 더듬거릴 경우를 대비해서 여기에 남겨두겠습니다.

def classMethods(the_class,class_only=False,instance_only=False,exclude_internal=True):

    def acceptMethod(tup):
        #internal function that analyzes the tuples returned by getmembers tup[1] is the 
        #actual member object
        is_method = inspect.ismethod(tup[1])
        if is_method:
            bound_to = tup[1].im_self
            internal = tup[1].im_func.func_name[:2] == '__' and tup[1].im_func.func_name[-2:] == '__'
            if internal and exclude_internal:
                include = False
            else:
                include = (bound_to == the_class and not instance_only) or (bound_to == None and not class_only)
        else:
            include = False
        return include
    #uses filter to return results according to internal function and arguments
    return filter(acceptMethod,inspect.getmembers(the_class))

위 중 어느 것도 나에게 통하지 않았다.

pytest를 작성하는 동안 이 문제가 발생했습니다.

제가 찾은 유일한 회피책은 다음과 같습니다.

1 - 다른 디렉토리를 생성하여 모든 .py 파일을 저장합니다.

2- 내 pytest에 대해 별도의 디렉토리를 만든 후 관심 있는 클래스를 가져옵니다.

에 의해,의 최신의 를 취득할 수 후, 「메서드명」을 사용할 수. 메서드 이름을 변경한 후 사용할 수 있습니다.print(dir(class))확인해 주세요.

inspect.ismethod 및 dir 및 getatr를 사용합니다.

 import inspect
 class ClassWithMethods:
    
    def method1(self):
        print('method1')
    def method2(self):
        print('method2')

obj=ClassWithMethods()

method_names = [attr for attr in dir(obj) if inspect.ismethod(getattr(obj,attr))

print(method_names)

출력:

[[('method1', <bound method ClassWithMethods.method1 of <__main__.ClassWithMethods object at 0x00000266779AF388>>), ('method2', <bound method ClassWithMethods.method2 of <__main__.ClassWithMethods object at 0x00000266779AF388>>)]]

이것은 단지 관찰일 뿐이다.문자열 객체의 메서드인 것 같습니다.

str_1 = 'a'
str_1.encode('utf-8')
>>> b'a'

단, str1에서 메서드를 검사하면 빈 목록이 반환됩니다.

inspect.getmember(str_1, predicate=inspect.ismethod)
>>> []

그래서, 내가 틀렸을지도 모르지만, 이 문제는 간단하지 않아 보인다.

메서드 목록을 작성하려면 일반적인 괄호 없이 메서드 이름을 목록에 입력합니다.이름을 삭제하고 괄호를 붙여 메서드를 호출합니다.

    def methodA():
        print("@ MethodA")

    def methodB():
        print("@ methodB")

    a = []
    a.append(methodA)
    a.append(methodB)
    for item in a:
        item()

이것처럼만.

pprint.pprint([x for x in dir(list) if not x.startswith("_")])
class CPerson:
    def __init__(self, age):
        self._age = age

    def run(self):
        pass

    @property
    def age(self): return self._age

    @staticmethod
    def my_static_method(): print("Life is short, you need Python")

    @classmethod
    def say(cls, msg): return msg


test_class = CPerson
# print(dir(test_class))  # list all the fields and methods of your object
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ == 'function' and not name.startswith('__')])
print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ != 'function' and not name.startswith('__')])

산출량

[('run', <function CPerson.run at 0x0000000002AD3268>)]
[('age', <property object at 0x0000000002368688>), ('my_static_method', <staticmethod object at 0x0000000002ACBD68>), ('say', <classmethod object at 0x0000000002ACF0B8>)]

python 클래스의 메서드만 나열하는 경우

import numpy as np
print(np.random.__all__)

언급URL : https://stackoverflow.com/questions/1911281/how-do-i-get-list-of-methods-in-a-python-class

반응형