【发布时间】:2012-01-24 01:57:35
【问题描述】:
我有一个类,出于继承原因,我将数据存储在列表中。我想知道,并且我已经完成了谷歌搜索,除了创建 getter/setter 函数和属性来为该列表中的元素提供别名之外,是否还有更简洁的方法?
例如...
class Serializable(object):
"""Adds serialization to from binary string"""
def encode(self):
"""Pack into struct"""
return self.encoder.pack(*self)
def decode(self, data_str):
"""Unpack from struct"""
self.data = self.encoder.unpack(data_str)
return self.data
class Ping(Serializable):
encoder = Struct("!16sBBBL")
def __init__(self, ident=create_id(), ttl=TTL, hops=0, length=0):
self.data = [ident, 1, ttl, hops, length]
self.ident = property(self.data[0])
def __getitem__(self, index):
return self.data[index]
@property
def ident(self):
return self.data[0]
@ident.setter
def ident(self, value):
self.data[0] = value
@property
def protocol(self):
return self.data[1]
@protocol.setter
def protocol(self, protocol):
self.data[1]
我希望使用更紧凑的解决方案来引用 object.ident,同时保持上述打包和解包的能力。
【问题讨论】:
-
根本不是问题,但我将进一步对 Ping 进行多次子类化并添加成员。
-
欢迎来到 StackOverflow。我为您格式化了您的代码(“{}”按钮)。第一次重新格式化是免费的 ;-)
-
谢谢@Johnsyweb 不会让它再次发生 :)
-
这并不能回答您提出的问题,但它可能会解决您的问题:不要编写自己的序列化,使用Pickle。
-
我可以定义如何通过 pickle 序列化数据吗?我必须遵循已定义的二进制格式。
标签: python properties alias