Python类中出现错误“listed is not defined”

2024-09-30 12:14:20 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么在下面的代码段中会出现错误listed is not defined

import socket,select
from threading import *
import time

neighbours=[]
def neighbourfuncall():
    print('In neighbours')

class pyserver(Thread):
    dictn={}
    HOST=socket.gethostname()
    PORT=8888
    buf=1024
    ADDR=(HOST,PORT)
    listed=[]
    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.bind(ADDR)    
    sock.listen(30)

    def __init__(self):
        self.interval=6
        listed.append(sock)
        thread=threading.Thread(target=neighbourfuncall,args=())
        thread.daemon=True
        thread.start()
    def run(self):
        while True:
            sel,out,spl=select.select(listed,[],[],15.0)
            for s in sel:
                if s==sock:
                    client,address=sock.accept()
                    listed.append(client)
                    dest=client.recv(buf)
                    dictn[client]=dest      
                else:
                    pass

serv=pyserver()  
serv.run()

Tags: importselfclientdefsocketselectthreadsock
2条回答

在类中,需要使用self.list.append(smth)。必须使用self访问所有类变量

顺便说一下,套接字操作必须在__init__()中。你最好这样做:

def __init__(self):
    self.smth=socket()
    self.other=[]
    self.smth.DoSomething()
def Hello(self):
    self.other.append("Hello") #just example

必须使用以下语法访问listed

pyserver.listed = ["I need to study more Python!"]

因为它是一个静态类变量

相关问题 更多 >

    热门问题