自我定义的问题

时间:2012-04-27 22:05:50

标签: python

File "clienttest.py", line 3, in <module>
   x = handle.Client()
File "/home/tmac/Handle/handle.py", line 131, in __init__
   Task.CLT_UPDATE:self.__clt_updates,
AttributeError: 'Client' object has no attribute '_Client__clt_updates'

我的代码在创建实例时抛出此错误但该函数存在。它似乎是在将_Client添加到它之前,我无法弄清楚为什么

继承人的课程定义

class Client(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        #create task q
        self.tasks = Queue.Queue(maxsize=0)
        print str(self)
        #create database
        self.database = server.Database()
        self.database.loadconfig()

        #create networking
        self.network = network.Network(self.tasks)

        #put startup tasks
        self.network.cmd_q.put(NetworkCommand(NetworkCommand.CONNECT,('127.0.0.1',self.database.config['Handle']['port'])))

        #create gui
        self.gui = gui.Gui(self)
        #define task handlers
        self.handlers = {
                Task.CLT_UPDATE:self.__clt_updates,
                            ^----The problem seems to be here--------^
                Task.CLT_INPUT:self.__clt_input,
                Task.CLT_LINEUP:self.__clt_lineup
                }

        #define alive flag
        self.alive = threading.Event()
        self.alive.set()

        #setup logging
        logging.basicConfig(level=self.loglvl, filename='client.log', format='%(asctime)s %(name)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
        self.log = logging.getLogger('CLIENT')



        def run(self):
            self.network.start()
            self.gui.initscreen()
            while self.alive.isSet():
                try:
                    task = self.tasks.get(True, 0.1)
                    self.log.debug('Got Task: ' + task.stype[task.type])
                    self.handlers[task.type](task)

                except Queue.Empty:
                    pass


        def addtask(self, task):
            self.tasks.put(task)

        def __clt_updates(self, task):
            raise NotImplemented()

        def __clt_input(self, task):
            pack = Packet(Packet.INPUT,task.data)
            self.network.cmd_q.put(NetworkCommand(NetworkCommand.SEND,pack))
            self.log.debug(':[H]Sent Command: ' + task.data)

        def __clt_lineup(self, task):
            self.gui.addline(task.data)
            self.log.debug(':[H]Line Update: ' + task.data)

1 个答案:

答案 0 :(得分:4)

Python中的双下划线导致Python name mangling在运行时启动。名称修改将为类名中的每个方法添加类名,名称以2个下划线开头。如果你想要没有名称修改的私有方法,请使用单个下划线。

如下面评论中所述,您看起来也有缩进问题。我的猜测是你打算将这些方法创建为类成员,但正如问题在这里有的那样,它们实际上是在__init__下缩进的。