Python3 - 导入和重写方法

标签 python sockets import overriding

server.py中,我有两个类,Server类和ClientThread类,其方法为processCmd。当我将此代码导入到新的 Proxy 类时,我想重写此方法。 怎么做?

这是服务器.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

最佳答案

您无法重写 Server 类中的 processCmd 方法。您还必须导入 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

关于Python3 - 导入和重写方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22401625/

相关文章:

python - 使用 imp 导入模块

csv - 如何将 csv 文件编码转换为 utf-8

Python - 使用 Numpy 进行相关性测试

python - DataFrame的一列为字符串时设置WithCopyWarning

c++ - 在特定网络接口(interface) Linux/Unix 上使用 C++ TCP 客户端套接字

javascript - 多种引用导出属性方式的区别

c - linux 2.6中的posix aio是否支持套接字文件描述符?

python - 为什么我不能用 np.zeros 初始化一个数组,然后将元素更改为数组?

Python:Image.frombytes() 参数

python - 如何从外部导入到模块中