我有一些运行良好的 python 3.4 代码:
def run():
m = 0
while m != 1:
p = input('Please choose p: ')
p = makeInt(p)
#Some other code
print(p)
m = makeInt(input('Enter 1 if you would like to quit: '))
def makeInt(i):
try:
i = int(i)
except ValueError:
i = input('Incorrect input! Enter your answer: ')
i = makeInt(i)
return i
#Some other functions
if __name__ == '__main__':
run()
我想将所有这些代码放在一个类中(可能除了 if __name__ ==
...)当我将所有代码包括 if __name__ ==
时。 ..在这样的类(class)中:
class Foo(object):
def run(self):
m = 0
while m != 1:
p1 = input('Please choose p: ')
p1 = self.makeInt(p1)
#Some other code
print(p1)
m = self.makeInt(input('Enter 1 if you would like to quit: '))
def makeInt(self, i):
try:
i = int(i)
except ValueError:
i = input('Incorrect input! Enter your answer: ')
i = self.makeInt(i)
return i
#Some other functions and stuff
if __name__ == '__main__':
run()
我收到以下错误:TypeError: run() 缺少 1 个必需的位置参数:'self'
。当我从 run()
中删除 self 参数时,它会一直运行,直到调用 makeInt()
为止,然后我得到: NameError: name 'makeInt' is not Defined
。如果我将 if 语句从类中取出并调用 Foo.run()
,我会得到同样的错误。我在这个程序的前面还有一些其他代码,当我从同一个类中的另一个函数调用一个类的函数时,它们会起作用。我意识到我不必将所有代码放在一个类中,但在本例中我想这样做。为什么我会收到这些错误?我该怎么做才能将我的工作代码放入类中?
最佳答案
正如其他人提到的,通过将函数放入类中,您已将它们设为方法,这意味着它们需要此类的实例作为第一个参数。因此,您确实可以使用 Foo().run()
调用 run
方法,因为 Foo()
将创建 Foo 的实例
.
另一种方法(例如,如果您除了封装之外不需要该类)是将它们设置为 static ,使用staticmethod
装饰器:
class Foo(object):
@staticmethod
def run():
...
@staticmethod
def makeInt(i):
...
if __name__ == '__main__':
Foo.run() # don't need an instance as run is static
在Python中,方法可以是静态的,即不需要任何特殊参数,类方法,即第一个参数是类本身,或者是标准方法,即第一个参数是类的实例。
关于python - 从主 python 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29066657/