2016-08-30 21 views
0

我有一个名为valueType.py使用在另一个文件中的其他类中定义的定义 - 蟒蛇

文件,它包含以下内容:

class SInt8(ValueType): 
    # Set _format as big endian signed char(1 byte) 
    _format = '>b' 

class UInt8(ValueType): 
    # Set _format as big endian unsigned char(1 byte) 
    _format = '>B' 

class SInt16(ValueType): 
    # Set _format as big endian signed short(2 bytes) 
    _format = '>h' 

class UInt16(ValueType): 
    # Set _format as big endian unsigned short(2 bytes) 
    _format = '>H' 

class SInt32(ValueType): 
    # Set _format as big endian signed int(4 bytes) 
    _format = '>i' 

class UInt32(ValueType): 
    # Set _format as big endian unsigned int(4 bytes) 
    _format = '>I' 

class Real32(ValueType): 
    # Set _format as big endian float(4 bytes) 
    _format = '>f' 

而且我还有一个文件,我们只是把它parser.py。在parser.py中,我定义了一个名为parameter的对象,该对象具有一个称为parameter.values的属性。

parameter.values包含原始十六进制值,我需要将它们转换为十进制格式,我打算使用struct.unpack(fmt, string)。 我的问题是,我怎样才能使用_formatvalueType.py里面的定义parser.py

valueType.py导入到parser.py,他们都在同一目录中

回答

0

简单,只是做X._format,其中X是你的一个类或它的一个实例

这里是一个说明性的例子

>>> class Test(object): 
     _format = "test" 


>>> Test._format 
'test' 
>>> t=Test() 
>>> t._format 
'test' 
>>> 

没有什么是真正的私人蟒蛇,如果有什么困扰你是_这是只有绅士协议说“不要使用它ou这个类/模块“。但是如果你知道有东西在那里,你可以使用它。

所以你的情况,这将是例如

#parser.py 
import valueType 
... 
x = struct.unpack(valueType.SInt8._format, parameter.values) 

如果是所有的,也许一本字典是一个更好的选择

valueType.py

你会使用这些类
formatType = { 
     "SInt8":'>b', 
     "UInt8":'>B', 
     "SInt16":'>h', 
     "UInt16":'>H', 
     "SInt32":'>i', 
     "UInt32":'>I', 
     "Real32":'>f' 
    } 

parser.py

from valueType import formatType 
... 
x = struct.unpack(formatType["SInt8"], parameter.values)  
相关问题