Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 公开类的内部方法并使用它们_Python_Python 2.7 - Fatal编程技术网

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.')