Python 公开类的内部方法并使用它们
假设我有一门课是这样的:Python 公开类的内部方法并使用它们,python,python-2.7,Python,Python 2.7,假设我有一门课是这样的: class Shell: def cat(self, file): try: with open(file, 'r') as f: print f.read() except IOError: raise IOError('invalid file location: {}'.format(f)) def echo(self, message): print message def ls
class Shell:
def cat(self, file):
try:
with open(file, 'r') as f:
print f.read()
except IOError:
raise IOError('invalid file location: {}'.format(f))
def echo(self, message):
print message
def ls(self, path):
print os.listdir(path)
在javascript上下文中,您可能能够执行类似于“Class”[method_name]()
的操作,这取决于事物的结构。我正在寻找类似python的东西,使其成为“模拟操作系统”。例如:
现在,他们可以输入这样的内容
$crow: cat ../my_text
。。。在幕后,我们得到了:
shell.cat('../my_text')
类似地,我希望能够在键入help
时打印该类中存在的所有方法定义。例如:
$crow: help\n
> cat (file)
> echo (message)
> ls (path)
这样的事情在python中可以实现吗?您可以使用内置函数公开对象的所有成员。这可能是为用户列出这些内容的最简单方法。如果您只打算打印到
stdout
,也可以调用help(shell)
,它将打印您的类成员以及docstring等等<代码>帮助实际上只适用于交互式解释器,因此您最好使用vars
和\uuuu doc\uuu
属性编写自己的帮助输出程序,该属性神奇地添加到带有docstring的对象中。例如:
class Shell(object):
def m(self):
'''Docstring of C#m.'''
return 1
def t(self, a):
'''Docstring of C#t'''
return 2
for name, obj in dict(vars(Shell)).items():
if not name.startswith('__'): #filter builtins
print(name, '::', obj.__doc__)
要选择并执行对象的特定方法,可以使用,它通过名称从对象中获取属性(如果存在)。例如,要选择并运行没有参数的简单函数:
fname = raw_input()
if hasattr(shell, fname):
func = getattr(shell, fname)
result = func()
else:
print('That function is not defined.')
当然,您可以首先标记用户输入,以便根据需要将参数传递给函数,例如cat
示例:
user_input = raw_input().split() # tokenize
fname, *args = user_input #This use of *args syntax is not available prior to Py3
if hasattr(shell, fname):
func = getattr(shell, fname)
result = func(*args) #The *args syntax here is available back to at least 2.6
else:
print('That function is not defined.')
先生,你帮了大忙。谢谢你的帮助。
user_input = raw_input().split() # tokenize
fname, *args = user_input #This use of *args syntax is not available prior to Py3
if hasattr(shell, fname):
func = getattr(shell, fname)
result = func(*args) #The *args syntax here is available back to at least 2.6
else:
print('That function is not defined.')