1

我正在做一个智能家居项目。我有很多东西,比如一些 XBee readios、LED、GPS 同步时钟、水计数器等。我尝试使用 OOP 方法,所以我创建了许多类和子类。现在您在代码中所要做的就是定义硬件,通过类内置函数将其连接到父级并享受。要获得一个想法:

coordinator = XBee24ZBCoordinator('/dev/ttyS1', 115200,
    "\x00\x13\xA2\x00\x40\x53\x56\x23", 'coord')
spalnya = XBee24ZBRemote('\x00\x13\xA2\x00\x40\x54\x1D\x12', 'spalnya')
spalnya.connectToCoordinator(coordinator)
vannaya = XBee24ZBRemote('\x00\x13\xA2\x00\x40\x54\x1D\x17', 'vannaya')    
vannaya.connectToCoordinator(coordinator)
led = LED()
led.connectTo(spalnya.getPin('DO4'), 'DO')
led.on()
led.off()

但是,我不想在代码中这样做。我想要一个ini文件来定义这个“网络”的拓扑。因此,我希望这个文件可以被人类阅读和编辑。逻辑选择是 ini (在手动编辑配置文件时,与 ej json 相比,json 至少对我来说不是超级友好)。现在,我得到了:

[xbee-coordinator]
type = XBee24ZBCoordinator
name = coord
comport = COM4
comspeed = 115200

我可以创建一个函数 BuildNetwork('my.ini'),它将读取并创建所需的对象实例和它们之间的连接。我该怎么做?有一个类 XBee24ZBCoordinator,但我从 ini 得到的只是一个字符串......

4

1 回答 1

1

You have two options:

  • Define all these classes in a module. Modules are just objects, so you can use getattr() on them:

    import types
    
    instance = getattr(types, typename)(arguments)
    
  • Store them all in a dictionary and look them up by name; you don't have to type out the name in a string, the class has a __name__ attribute you can re-use:

    types = {}
    
    class XBee24ZBCoordinator():
        # class definition
    
    types[XBee24ZBCoordinator.__name__] = XBee24ZBCoordinator
    

If these are defined in the 'current' module, the globals() function returns a dictionary too, so globals()['XBee24ZBCoordinator'] is a reference to the class definition as well.

于 2013-01-12T18:15:41.523 回答