Python3 - 导入和覆盖方法

时间:2014-03-14 09:57:53

标签: python sockets import override

server.py我有两个班级,班级ServerClientThread班级processCmd。我想在将此代码导入新的Proxy类时重写此方法。 怎么做?

这是server.py:

class ClientThread( threading.Thread, socket.socket ):
    #(some code)
    def processCmd( self, cmd ):
        if 'quit' == cmd:
            self.writeline(str('Ok, bye'))
            QUIT = True
            done = True
        elif 'bye' == str(cmd):
            self.writeline(str('Ok, bye'))
            done = True
        else:
            print(cmd)
#
class Server:
    #(some code)
    def run( self ):
       self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
       self.sock.bind( ( '127.0.0.1', 5050 ) )
       new_thread = ClientThread( client )
       print('Incoming Connection. Started thread ', end=' ')
       self.thread_list.append( new_thread )
       new_thread.start()

在另一个文件中是主要代码:

import server
#
class Proxy( server.Server):
    def processCmd( self, cmd ):
        if 'quit' == cmd:
            self.writeline(str('Another quit'))
            QUIT = True
            done = True
        elif 'bye' == str(cmd):
            self.writeline(str('Another bye'))
            done = True
        else:
            print(cmd)
    pass

2 个答案:

答案 0 :(得分:1)

您无法覆盖processCmd课程中的Server方法。您还必须导入ClientThread并将其子类化。

import server

class Proxy( server.Server):
    def run( self ):
       self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
       self.sock.bind( ( '127.0.0.1', 5050 ) )
       new_thread = CustomClientThread( client )
       print('Incoming Connection. Started thread ', end=' ')
       self.thread_list.append( new_thread )
       new_thread.start()
    pass

class CustomClientThread(server.ClientThread)
    def processCmd( self, cmd ):
        #override here

如果你不想覆盖整个run方法,你应该在基类中改变它,这样clientThread的类型就可以在方法的一边设置。

class Server:
    thread = ClientThread

    #(some code)
    def run( self ):
       self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
       self.sock.bind( ( '127.0.0.1', 5050 ) )
       new_thread = thread( client )
       print('Incoming Connection. Started thread ', end=' ')
       self.thread_list.append( new_thread )
       new_thread.start()

然后子类看起来像这样,run方法保持不变。

class Proxy( server.Server):
    thread = CustomClientThread

答案 1 :(得分:0)

如果要覆盖ClientThread的方法,则可以覆盖为

class OverrideClientThread(server.ClientThread):
    def processCmd(self, cmd):
        # call super
        server.ClientThread.processCmd(self, cmd)
        #do something.