Python:函数不带参数 [英] Python:Function takes no arguments
问题描述
运行此代码时,我收到错误消息:
File "Start.py", line 22, in <module>
c.lo()
TypeError: lo() takes no arguments (1 given)
我不知道为什么我会收到此错误,有人可以解释一下吗? 我知道这是说我在调用该函数时输入了一个参数,但我不明白为什么会这样?
如果有人可以阐明这个问题,那就太好了.
import subprocess as sp
import Tkinter as Tk
from Tkinter import *
root = Tk()
text = Text(root)
class Console:
def Start():
proc = sp.Popen(["java", "-Xmx1536M", "-Xms1536M", "-jar", ".jar"],stdin=sp.PIPE,stdout=sp.PIPE,)
def lo():
while True:
line = proc.stdout.readline()
text.insert(INSERT,line)
text.pack()
if (line == "Read Time Out"):
proc.stdin.write('stop')
if (line == "Unloading Dimension"):
text.insert(INSERT,"Ready for command")
text.pack()
c = Console()
c.Start()
c.lo()
root.mainloop()
简而言之,这是因为lo()
是类Console
的方法,该方法始终将实例作为第一个参数传递.因此,lo()
必须定义一个参数(通常称为self
)来保存该参数:
class Console:
def start(self): # functions and methods should have lowercase names
self.proc = sp.Popen(...)
def lo(self):
line = self.proc.stdout.readline()
...
您的Start()
通话效果很好,我感到很惊讶;它有同样的问题.
When I run this code I get the error message:
File "Start.py", line 22, in <module>
c.lo()
TypeError: lo() takes no arguments (1 given)
I don't know exactly why I am getting this error could someone please explain? I know it's saying that I put an argument when calling that function but I don't understand why that is?
If someone could shed some light on this issue that would be great.
import subprocess as sp
import Tkinter as Tk
from Tkinter import *
root = Tk()
text = Text(root)
class Console:
def Start():
proc = sp.Popen(["java", "-Xmx1536M", "-Xms1536M", "-jar", ".jar"],stdin=sp.PIPE,stdout=sp.PIPE,)
def lo():
while True:
line = proc.stdout.readline()
text.insert(INSERT,line)
text.pack()
if (line == "Read Time Out"):
proc.stdin.write('stop')
if (line == "Unloading Dimension"):
text.insert(INSERT,"Ready for command")
text.pack()
c = Console()
c.Start()
c.lo()
root.mainloop()
In short, that is because lo()
is a method of the class Console
which is always passed the instance as first argument. So lo()
must define a parameter (mostly called self
) to hold that argument:
class Console:
def start(self): # functions and methods should have lowercase names
self.proc = sp.Popen(...)
def lo(self):
line = self.proc.stdout.readline()
...
I am surprised that your Start()
call worked; it has the same issue.
这篇关于Python:函数不带参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!