在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/