Приятно печатать "публичные" методы класса Python - PullRequest
1 голос
/ 21 мая 2019

Я пытаюсь разработать API в python, используя класс:

class SimulationApi(object):

  def hello(self):
    return "Hi"

  def echo(self, string):
    return string

  def get_foo(self):
    return self.foo

  def __init__(self):
    self.foo = 50

И я хотел бы вывести на консоль список доступных общедоступных методов, определенных классом.Есть ли способ сделать это автоматически, что также подберет параметры метода?В идеале вывод должен выглядеть следующим образом:

SimulationApi: 
    get_foo()
    echo(string)
    hello()

Пока что мое решение таково, но оно неполное и может быть неправильным направлением.

print("SimulationApi: \n\t{}\n".format("\n\t".join([x+"()" for x in dir(SimulationApi) if not x.startswith("__")]))

1 Ответ

2 голосов
/ 23 мая 2019

Вы можете использовать inspect модуль:

class SimulationApi(object):

  def hello(self):
    return "Hi"

  def echo(self, string):
    return string

  def get_foo(self):
    return self.foo

  def __init__(self):
    self.foo = 50


import inspect
inspect.getmembers(SimulationApi)

Вернет:

[('__class__', type),
 ('__delattr__', <slot wrapper '__delattr__' of 'object' objects>),
 ('__dict__',
  mappingproxy({'__module__': '__main__',
                'hello': <function __main__.SimulationApi.hello(self)>,
                'echo': <function __main__.SimulationApi.echo(self, string)>,
                'get_foo': <function __main__.SimulationApi.get_foo(self)>,
                '__init__': <function __main__.SimulationApi.__init__(self)>,
                '__dict__': <attribute '__dict__' of 'SimulationApi' objects>,
                '__weakref__': <attribute '__weakref__' of 'SimulationApi' objects>,
                '__doc__': None})),
 ('__dir__', <method '__dir__' of 'object' objects>),
 ('__doc__', None),
 ('__eq__', <slot wrapper '__eq__' of 'object' objects>),
 ('__format__', <method '__format__' of 'object' objects>),
 ('__ge__', <slot wrapper '__ge__' of 'object' objects>),
 ('__getattribute__', <slot wrapper '__getattribute__' of 'object' objects>),
 ('__gt__', <slot wrapper '__gt__' of 'object' objects>),
 ('__hash__', <slot wrapper '__hash__' of 'object' objects>),
 ('__init__', <function __main__.SimulationApi.__init__(self)>),
 ('__init_subclass__', <function SimulationApi.__init_subclass__>),
 ('__le__', <slot wrapper '__le__' of 'object' objects>),
 ('__lt__', <slot wrapper '__lt__' of 'object' objects>),
 ('__module__', '__main__'),
 ('__ne__', <slot wrapper '__ne__' of 'object' objects>),
 ('__new__', <function object.__new__(*args, **kwargs)>),
 ('__reduce__', <method '__reduce__' of 'object' objects>),
 ('__reduce_ex__', <method '__reduce_ex__' of 'object' objects>),
 ('__repr__', <slot wrapper '__repr__' of 'object' objects>),
 ('__setattr__', <slot wrapper '__setattr__' of 'object' objects>),
 ('__sizeof__', <method '__sizeof__' of 'object' objects>),
 ('__str__', <slot wrapper '__str__' of 'object' objects>),
 ('__subclasshook__', <function SimulationApi.__subclasshook__>),
 ('__weakref__', <attribute '__weakref__' of 'SimulationApi' objects>),
 ('echo', <function __main__.SimulationApi.echo(self, string)>),
 ('get_foo', <function __main__.SimulationApi.get_foo(self)>),
 ('hello', <function __main__.SimulationApi.hello(self)>)]

Примечание: Ваши методы (методы, которые вам нравятсядля получения информации) также SimulationApi словарь классов __dict__.

Вы можете получить полный код для вашей echo функции следующим образом:

import inspect
lines = inspect.getsource(SimulationApi.echo)
print(lines)

  def echo(self, string):
    return string
...