Znajdowanie metod jakie posiada obiekt Pythona

Biorąc pod uwagę dowolny obiekt Pythona, czy istnieje łatwy sposób na uzyskanie listy wszystkich metod, które ten obiekt posiada?

LUB,

Jeśli nie jest to możliwe, czy istnieje przynajmniej łatwy sposób sprawdzenia, czy ma określoną metodę inną niż zwykłe sprawdzenie, czy wystąpi błąd podczas wywoływania metody?

Author: codeforester, 2008-08-29

15 answers

Wygląda na to, że możesz użyć tego kodu, zastępując "obiekt" obiektem, który Cię interesuje: -

[method_name for method_name in dir(object)
 if callable(getattr(object, method_name))]

Odkryłem to na tej stronie, mam nadzieję, że powinno to dostarczyć więcej szczegółów!

 361
Author: ljs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-09 08:41:55

Możesz użyć wbudowanej funkcji dir(), Aby uzyskać listę wszystkich atrybutów, które posiada moduł. Spróbuj tego w wierszu poleceń, aby zobaczyć, jak to działa.

>>> import moduleName
>>> dir(moduleName)

Możesz również użyć funkcji hasattr(module_name, "attr_name"), aby dowiedzieć się, czy moduł ma określony atrybut.

Aby uzyskać więcej informacji, zapoznaj się z przewodnikiem po introspekcji Pythona .
 163
Author: Bill the Lizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-26 17:51:07

Najprostszą metodą jest użycie dir(objectname). Wyświetli wszystkie metody dostępne dla tego obiektu. Fajna sztuczka.

 42
Author: Pawan Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-10 12:57:55

Aby sprawdzić, czy ma określoną metodę:

hasattr(object,"method")
 25
Author: Bill the Lizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-30 04:12:14

Poza bardziej bezpośrednimi odpowiedziami, byłbym niedbały, gdybym nie wspomniał iPython . Naciśnij "tab", aby zobaczyć dostępne metody z autocompletion.

A gdy już znajdziesz metodę, spróbuj:

help(object.method) 

Aby zobaczyć pydocs, podpis metody itp.

Ahh... REPL .
 22
Author: jmanning2k,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-01 08:34:29

Wierzę, że to, czego chcesz, to coś takiego:

Lista atrybutów z obiektu

Moim skromnym zdaniem, wbudowana funkcja dir() może wykonać tę pracę za Ciebie. Pobrane z help(dir) wyjścia w powłoce Pythona:

Dir(...)

dir([object]) -> list of strings

Jeśli wywołane bez argumentu, zwracają nazwy w bieżącym zakresie.

Else, zwraca alfabetyczną listę nazw zawierającą (niektóre) atrybuty danego obiektu oraz atrybuty osiągalne z niego.

Jeśli obiekt dostarcza metodę o nazwie __dir__, zostanie użyta; w przeciwnym razie domyślna logika dir () jest używana i zwraca:

  • Dla obiektu modułu: atrybuty modułu.
  • Dla obiektu klasy: jego atrybuty i rekurencyjnie atrybuty jego baz.
  • dla każdego innego obiektu: jego atrybutów, atrybutów klasy oraz rekurencyjnie atrybuty klas bazowych swojej klasy.

Na przykład:

$ 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']

Kiedy sprawdzałem twój problem, postanowiłem zademonstrować mój ciąg myśli, z lepszym formatowaniem wyjścia dir().

Dir_attributes.py (Python 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 (Python 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("")

Mam nadzieję, że się przyczyniłem :).

 20
Author: ivanleoncz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-22 21:09:51

Jeśli chcesz metody , powinieneś użyć metody inspect.ismethod .

Dla nazw metod:

import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]

Dla samych metod:

import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]

Czasami inspect.isroutine może być również użyteczny (dla Wbudowanych rozszerzeń C, Cython bez dyrektywy "wiążącej" kompilatora).

 8
Author: paulmelnikow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-09 07:37:39

Problem ze wszystkimi wskazanymi tutaj metodami polega na tym, że nie można być pewnym, że metoda nie istnieje.

W Pythonie można przechwycić wywołanie kropki przez __getattr__ i __getattribute__, co umożliwia tworzenie metody "at runtime"

Exemple:

class MoreMethod(object):
    def some_method(self, x):
        return x
    def __getattr__(self, *args):
        return lambda x: x*2

Jeśli ją wykonasz, możesz wywołać metodę nieistniejącą w słowniku obiektu...

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

I dlatego używasz łatwiej prosić o przebaczenie niż pozwolenie w Pythonie.

 5
Author: Cld,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-23 18:18:40

Najprostszym sposobem uzyskania listy metod dowolnego obiektu jest użycie polecenia help().

%help(object)

Wyświetli listę wszystkich dostępnych / ważnych metod powiązanych z tym obiektem.

Na przykład:

help(str)
 4
Author: Paritosh Vyas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-26 19:46:06

Otwórz powłokę bash (ctrl + alt + T na Ubuntu). Uruchom powłokę python3. Utwórz obiekt do obserwacji metod. Po prostu dodaj kropkę i naciśnij dwa razy "tab", a zobaczysz coś takiego:

 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 times
 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(           
 4
Author: Valery Ramusik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-30 20:43:46

Można utworzyć funkcję getAttrs, która zwróci wywoływalne nazwy właściwości obiektu

def getAttrs(object):
  return filter(lambda m: callable(getattr(object, m)), dir(object))

print getAttrs('Foo bar'.split(' '))

That ' d return

['__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']
 2
Author: james_womack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-24 15:37:28

Nie ma wiarygodnego sposobu na wylistowanie wszystkich metod obiektu. dir(object) jest zwykle użyteczne, ale w niektórych przypadkach może nie zawierać wszystkich metod. Według dir() Dokumentacja: "za pomocą argumentu spróbuj zwrócić listę ważnych atrybutów dla tego obiektu."

Sprawdzenie istnienia tej metody może być wykonane przez callable(getattr(object, method)), Jak już tam wspomniano.

 2
Author: aver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-16 12:13:18

... jest co najmniej łatwy sposób, aby sprawdzić, czy ma określoną metodę inną niż po prostu sprawdzanie, czy wystąpi błąd podczas wywoływania metody

Podczas Gdy " łatwiej prosić o przebaczenie niż pozwolenie " jest z pewnością sposobem Pythonicznym, czego szukasz Może:

d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
    d.get('foo')
# OUT: 'bar'
 1
Author: Bruno Bronosky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-26 14:51:55

Weź listę jako obiekt

obj = []

list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))

Otrzymujesz:

['__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']
 0
Author: Mahdi Ghelichi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-16 15:34:59

W celu wyszukania konkretnej metody w całym module

for method in dir(module) :
  if "keyword_of_methode" in method :
   print(method, end="\n")
 0
Author: user9467669,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-09 13:11:50