列出的错误"未定义"在Python类中

时间:2015-02-03 14:08:14

标签: python class

为什么我在以下代码段中收到错误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()

2 个答案:

答案 0 :(得分:2)

您必须使用以下语法访问listed

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

因为它是一个静态类变量。

答案 1 :(得分:1)

当你在课堂上时,你需要使用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