【发布时间】:2017-09-13 08:39:41
【问题描述】:
我有一个运行 while 循环命令提示符的类,我正在使用 dir() 和 getattr() 为命令 shell 动态创建方法列表。我想返回值,但是从动态调用的方法返回只是退出到主while循环,我该如何解决这个问题?
class myClass :
def __init__(self) :
self.commands = []
for x in dir(self) :
k = getattr( self, x )
if hasattr(k, '__func__') :
self.commands.append(x)
# strips off __init__ and __main__
self.commands = self.commands[2:]
def help(self, args=None) :
for x in self.commands :
####
#### The issue is here
print('Command: {}'.format(x))
f = getattr(self, x)('-h')
desc = f()
print('Description: {}'.format(desc))
...
return SomeValue
def cmd_b(self, args=None) :
if args == '-h' :
return 'Some description'
...
return SomeValue
def cmd_c(self, args=None) :
...
return SomeValue
def __main__(self) :
while True :
command = input(self.ENV['PS1'])
command += ' '
command = command.split()
print(command)
if len(command) > 1 :
print(command)
print(len(command))
args = command[1:]
command = command[0]
else :
command = command[0]
args = None
if command == 'exit' :
break
if command not in dir(self) :
print("Command `{}` not found".format(command))
continue
print(command)
f = getattr( self, command )(args)
x = f()
【问题讨论】:
-
你能修复缩进吗?
__main__功能已关闭 -
不是类的一部分 (myClass.__main__()),我并没有尝试发布整个代码,因为我已经发现我发布的内容可能不受欢迎。 @FrancescoMontesano
-
Francesco 说了什么。还看到
def myClass :SyntaxError: invalid syntax。你可能想要def myClass(object):。 -
哎呀应该是
class myClass如果我只是发布整个代码,它真的不会再长了,我想我添加的内容足以让它有意义 @jq170727 -
是的,请更正您的代码。在 StackOverflow 上总是尽力发布MCVE - Minimal, Complete, and Verifiable example
标签: python-3.x return-value getattr dynamic-method hasattr