推动价值从一个类别变为另一个类别

时间:2015-09-29 06:45:38

标签: python

我正在尝试为自己的硬件开发一种私有API。我想在两个单独的python文件中有两个类MainSimulations。我的Simulations类模拟来自某些第三方硬件的推送事件以进行调试。我想在我的Main中轻松接收这些推送。例如,如果我在Simulations中更改GPS坐标的值,我希望调用coordinatesDidChange()方法。我想尽量减少Main中的代码并执行Simulations中的所有基础设施内容。有什么想法吗?

Psedocode

class Main:
    def coordinatesDidChange(coordinates):
        # Do stuff with coordinates

class Simulations:
    coordinates = 0.0000
    coordinates = 0.2453

1 个答案:

答案 0 :(得分:0)

class Main(object):
    def notify_coordinates(self, long, lat):
        print 'Main received coordinates (%s,%s)' % (long, lat)

class Simulations(object):
    def __init__(self):
        self.observers = []
        self.coordinates = {'long' : 0.0000, 'lat' : 0.0000 }

    def append_observer(self, observer):
        self.observers.append(observer)

    def update_coordinates(self, long, lat):
        self.coordinates['long'] = long
        self.coordinates['lat'] = lat
        self.notify_observers('notify_coordinates', long, lat)

    def notify_observers(self, callback, *args, **kwargs):
        for observer in self.observers:
            if hasattr(observer, callback):
                getattr(observer, callback)(*args, **kwargs)

main = Main()

simulations = Simulations()
simulations.append_observer(main)

simulations.update_coordinates(0.0000,0.2453)