python函数必须有参数吗,Python:函数不带参数

博客内容涉及Python编程中的一个常见错误,即在调用类方法时未正确传递self参数。作者指出,`lo()`方法作为`Console`类的一部分,应该接受一个隐含的self参数,但代码中没有定义。修复这个问题的方法是在`lo()`方法定义中添加self参数。同时,文章还提及了`Start()`方法也存在同样的问题,但令人惊讶的是,它居然能正常运行。
摘要由CSDN通过智能技术生成

When I run this code I get the error message:

File "Start.py", line 22, in

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值