我以前是个c++程序员,几个月来一直潜心研究python,非常棒。我正在做一点代码移植,遇到了一个问题,我不确定最佳路径。剥猫皮的方法有很多种,但我正在寻找一些建议,看看什么是“最好的”和/或最适合做类似于下面c++代码部分的事情的方法。你知道吗
我把代码简化成了一个微不足道的“复制者”,只是为了强调正在发生的事情。 本质上,当某些事件发生时,服务器将调用一个定义良好的回调接口。当服务器被创建时,它被提供一个回调接口作为参数。你知道吗
在下面的例子中,客户机已经在自己身上实现了这些回调,因此在创建服务器时,它提供了*this指针。你知道吗
这在python中是类似的吗?任何建议都将不胜感激。你知道吗
#include <iostream>
// Client Feed Handler function Interface
class ClientFeedHandlersI
{
public:
virtual void HandlerFeed1() = 0;
virtual void HandlerFeed2() = 0;
};
// A very basic server
class Server
{
public:
Server(ClientFeedHandlersI& handlers)
: mHandlers(handlers) {}
void Start()
{
// Create some random events to illustrate
for (int i = 0; i < 10; ++i)
EventLoopHandler();
}
private:
void EventLoopHandler()
{
if (rand() % 10 > 5)
mHandlers.HandlerFeed1();
else
mHandlers.HandlerFeed2();
}
ClientFeedHandlersI& mHandlers;
};
// A really simple client
class Client : private ClientFeedHandlersI
{
public:
Client()
: mMyServer(*this)
{
mMyServer.Start();
}
private:
void HandlerFeed1() override { std::cout << "HandlerFeed1 called\n"; }
void HandlerFeed2() override { std::cout << "HandlerFeed2 called\n"; }
Server mMyServer;
};
int main()
{
auto c = Client();
}
下面是一个移植到python的尝试。请注意,在实际示例中,有20多个客户机提要处理程序函数,因此我希望使用@abstractmethod强制接口。你知道吗
# python 3.6
from abc import ABC, abstractmethod
class ClientFeedHandlersI(ABC):
def __init__(self):
pass
@abstractmethod
def handler_feed_1(self):
pass
@abstractmethod
def handler_feed_2(self):
pass
class Server:
def __init__(self, clientCallBacks:ClientFeedHandlersI):
self.clientCallBacks = clientCallBacks
def start(self):
for ii in range(10):
self.event_loop_handler()
def event_loop_handler(self):
import random
if random.randint(0,10) > 5:
self.clientCallBacks.handler_feed_1()
else:
self.clientCallBacks.handler_feed_2()
class Client(ClientFeedHandlersI):
def __init__(self):
self.server = Server(self)
self.server.start()
def handler_feed_1(self):
print("HandlerFeed1 called\n")
def handler_feed_2(self):
print("HandlerFeed2 called\n")
if __name__ == '__main__':
c = Client()
编辑:上面的代码示例现在按照c++代码工作。你知道吗
Python示例代码,在C++下在OP中工作。你知道吗
相关问题 更多 >
编程相关推荐