【问题标题】:How to call a class's method in python? [closed]如何在python中调用类的方法? [关闭]
【发布时间】:2014-12-05 18:46:34
【问题描述】:

我是 python 的新手,正在尝试编写一个 python 脚本,它需要两个命令行参数,对它们做一些事情,然后将输出返回到标准输出。

我的脚本是这样的:

class MyClass:
  def GET(self):
    #get the passed in arguments in arg1 and arg2
    return self.perform(arg1, arg2)

  def perform(self, arg1, arg2):
    return arg1+arg2

if __name__ == "__main__":
   #call the GET method of MyClass with all the arguments  
  • 如何将命令行参数sys.argv[1:] 传递给MyClassGET 方法?
  • GET的签名会从GET(self)变成GET(self, arg1, arg2)吗?

【问题讨论】:

  • 看来你已经有了答案!

标签: python command-line command-line-arguments


【解决方案1】:

你在那里写的是实例方法,需要一个实例来调用它们。 例如

x = MyClass() # create an instance of MyClass
x.GET()

但是,arg1arg2 从未初始化,因此您的 GET 方法不会知道它们是什么。如果要将它们传递给GET,则需要将它们指定为参数:

class MyClass:
  def GET(self, arg1, arg2):
    ...

然后你可以调用该方法

x.GET(sys.argv[1], sys.argv[2])

但这会使GET 变得毫无意义,因为它所做的只是将调用重定向到perform 方法。

如果您愿意,可以将argv 数组本身传递给GET。这将需要:

class MyClass:
  def GET(self, args):
     return self.perform(args[1], args[2])
  ...

x = MyClass()
x.GET(sys.argv)

如果你想将结果输出到stdout,你可以使用print。例如

print(x.GET(sys.argv))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多