Python 객체에 어떤 메서드가 있는지 찾기
-
09-06-2019 - |
문제
어떤 종류의 Python 개체가 주어지든 이 개체에 포함된 모든 메서드 목록을 쉽게 얻을 수 있는 방법이 있습니까?
또는,
이것이 가능하지 않다면 단순히 메소드가 호출될 때 오류가 발생하는지 확인하는 것 외에 특정 메소드가 있는지 확인하는 쉬운 방법이 있습니까?
해결책
이 코드를 사용하여 'object'를 관심 있는 객체로 바꿀 수 있는 것 같습니다.
object_methods = [method_name for method_name in dir(object)
if callable(getattr(object, method_name))]
나는 그것을 발견했다. 이 장소.바라건대, 이것이 좀 더 자세한 내용을 제공할 것입니다!
다른 팁
내장된 것을 사용할 수 있습니다. dir()
모듈이 가지고 있는 모든 속성의 목록을 가져오는 함수입니다.어떻게 작동하는지 보려면 명령줄에서 이것을 시도해 보세요.
>>> import moduleName
>>> dir(moduleName)
또한 다음을 사용할 수 있습니다. hasattr(module_name, "attr_name")
모듈에 특정 속성이 있는지 확인하는 함수입니다.
참조 Python 내부 검사 가이드 자세한 내용은.
가장 간단한 방법은 다음과 같습니다. dir(objectname)
.해당 개체에 사용할 수 있는 모든 메서드가 표시됩니다.멋진 트릭입니다.
특정 메서드가 있는지 확인하려면 다음을 수행하세요.
hasattr(object,"method")
나는 당신이 원하는 것이 다음과 같다고 믿습니다.
객체의 속성 목록
내 생각으로는 내장 함수는 dir()
당신을 위해 이 일을 할 수 있어요.에서 가져옴 help(dir)
Python Shell에서 출력:
디렉토리(...)
dir([object]) -> list of strings
인수 없이 호출하면 현재 범위의 이름을 반환합니다.
그렇지 않으면, 주어진 객체의 속성(일부)과 그 객체에서 도달할 수 있는 속성을 구성하는 알파벳순 이름 목록을 반환합니다.
객체가 다음과 같은 메소드를 제공하는 경우
__dir__
, 그것은 사용될 것입니다;그렇지 않으면 기본 DIR () 로직이 사용되어 반환됩니다.
- 모듈 객체의 경우:모듈의 속성.
- 클래스 객체의 경우:해당 속성과 재귀적으로 해당 기본의 속성입니다.
- 다른 개체의 경우:그것의 속성, 클래스의 속성 및 클래스 기본 클래스의 속성을 재귀 적으로.
예를 들어:
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "I am a string"
>>>
>>> type(a)
<class 'str'>
>>>
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'_formatter_field_name_split', '_formatter_parser', 'capitalize',
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
귀하의 문제를 확인하면서 저는 dir()
.
dir_attributes.py (파이썬 2.7.6)
#!/usr/bin/python
""" Demonstrates the usage of dir(), with better output. """
__author__ = "ivanleoncz"
obj = "I am a string."
count = 0
print "\nObject Data: %s" % obj
print "Object Type: %s\n" % type(obj)
for method in dir(obj):
# the comma at the end of the print, makes it printing
# in the same line, 4 times (count)
print "| {0: <20}".format(method),
count += 1
if count == 4:
count = 0
print
dir_attributes.py (파이썬 3.4.3)
#!/usr/bin/python3
""" Demonstrates the usage of dir(), with better output. """
__author__ = "ivanleoncz"
obj = "I am a string."
count = 0
print("\nObject Data: ", obj)
print("Object Type: ", type(obj),"\n")
for method in dir(obj):
# the end=" " at the end of the print statement,
# makes it printing in the same line, 4 times (count)
print("| {:20}".format(method), end=" ")
count += 1
if count == 4:
count = 0
print("")
내가 기여하길 바랍니다 :).
특별히 원하신다면 행동 양식, 당신은 사용해야합니다 검사 방법.
메소드 이름의 경우:
import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]
메소드 자체의 경우:
import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]
때때로 inspect.isroutine
유용할 수도 있습니다(내장, C 확장, "바인딩" 컴파일러 지시문이 없는 Cython의 경우).
Bash 쉘을 엽니다(Ubuntu에서는 Ctrl+Alt+T).python3 쉘을 시작하십시오.메소드를 관찰하기 위한 객체를 생성합니다.그 뒤에 점을 추가하고 "탭"을 두 번 누르면 다음과 같은 내용이 표시됩니다.
user@note:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> s = "Any object. Now it's a string"
>>> s. # here tab should be pressed twice
s.__add__( s.__rmod__( s.istitle(
s.__class__( s.__rmul__( s.isupper(
s.__contains__( s.__setattr__( s.join(
s.__delattr__( s.__sizeof__( s.ljust(
s.__dir__( s.__str__( s.lower(
s.__doc__ s.__subclasshook__( s.lstrip(
s.__eq__( s.capitalize( s.maketrans(
s.__format__( s.casefold( s.partition(
s.__ge__( s.center( s.replace(
s.__getattribute__( s.count( s.rfind(
s.__getitem__( s.encode( s.rindex(
s.__getnewargs__( s.endswith( s.rjust(
s.__gt__( s.expandtabs( s.rpartition(
s.__hash__( s.find( s.rsplit(
s.__init__( s.format( s.rstrip(
s.__iter__( s.format_map( s.split(
s.__le__( s.index( s.splitlines(
s.__len__( s.isalnum( s.startswith(
s.__lt__( s.isalpha( s.strip(
s.__mod__( s.isdecimal( s.swapcase(
s.__mul__( s.isdigit( s.title(
s.__ne__( s.isidentifier( s.translate(
s.__new__( s.islower( s.upper(
s.__reduce__( s.isnumeric( s.zfill(
s.__reduce_ex__( s.isprintable(
s.__repr__( s.isspace(
여기에 표시된 모든 방법의 문제점은 해당 방법이 존재하지 않는지 확인할 수 없다는 것입니다.
Python에서는 다음을 통해 점 호출을 가로챌 수 있습니다. __getattr__
그리고 __getattribute__
, "런타임에" 메소드 생성 가능
예:
class MoreMethod(object):
def some_method(self, x):
return x
def __getattr__(self, *args):
return lambda x: x*2
실행시키면 객체 사전에 존재하지 않는 메소드를 호출할 수 있게 되는데...
>>> o = MoreMethod()
>>> o.some_method(5)
5
>>> dir(o)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'some_method']
>>> o.i_dont_care_of_the_name(5)
10
그리고 이것이 바로 당신이 허락보다 용서를 구하는 것이 더 쉽다 파이썬의 패러다임.
모든 객체의 메소드 목록을 얻는 가장 간단한 방법은 다음을 사용하는 것입니다. help()
명령.
%help(object)
해당 개체와 관련된 사용 가능한/중요한 메서드가 모두 나열됩니다.
예를 들어:
help(str)
하나는 getAttrs
객체의 호출 가능한 속성 이름을 반환하는 함수
def getAttrs(object):
return filter(lambda m: callable(getattr(object, m)), dir(object))
print getAttrs('Foo bar'.split(' '))
그게 돌아올거야
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
'__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']
모든 객체의 메소드를 나열하는 신뢰할 수 있는 방법은 없습니다. dir(object)
일반적으로 유용하지만 어떤 경우에는 모든 방법을 나열하지 못할 수도 있습니다.에 따르면 dir()
선적 서류 비치: "라는 주장으로 시도 해당 객체에 대한 유효한 속성 목록을 반환합니다."
메소드가 존재하는지 확인하는 것은 다음과 같이 수행할 수 있습니다. callable(getattr(object, method))
거기에서 이미 언급했듯이.
...메서드가 호출될 때 오류가 발생하는지 단순히 확인하는 것 외에 특정 메서드가 있는지 확인하는 최소한의 쉬운 방법이 있습니까?
하는 동안 "허락보다 용서를 구하는 것이 더 쉽다"는 확실히 Pythonic 방식입니다. 아마도 당신이 찾고 있는 것은 다음과 같습니다.
d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
d.get('foo')
# OUT: 'bar'
목록을 객체로 사용
obj = []
list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))
당신은 다음을 얻습니다:
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
전체 모듈에서 특정 메소드를 검색하려면
for method in dir(module) :
if "keyword_of_methode" in method :
print(method, end="\n")