properties - Create a 'standard property' for class attributes in Python -


i have class, used translate binary stream human readable. want translate both ways, because send , receive binary messages. attributes of class made same way - take bytes startbyte stopbyte , decode them - made decision use property that. can make general "property" used when defining class attributes?

class packet(object):     def __init__(self, data):         self.data = data      def standard_getter(startbyte, stopbyte):         def getter(self):             return decode(self.data[startbyte:stopbyte])         return getter      def standard_setter(startbyte, stopbyte):         def setter(self, value):             self.data[startbyte:stopbyte] = encode(value)     return setter      # way define properties now:     protocol_type = property(standard_getter(16, 18), standard_setter(16, 18))     protocol_sub_type = property(standard_getter(18, 20), standard_setter(18, 20))      # way it:     protocol_type = property(standard_property(16, 18))     # or     protocol_type = standard_property(16, 18) 

i tried define function, takes 2 arguments , returns property(getter, setter), i'm stuck in giving "self" instance function. there nice way can make it?

have function produce both getter , setter, , return property object 2 functions:

def standard_property(startbyte, stopbyte):     def getter(self):         return decode(self.data[startbyte:stopbyte])     def setter(self, value):         self.data[startbyte:stopbyte] = encode(value)     return property(getter, setter) 

then use return value directly:

protocol_type = standard_property(16, 18) protocol_sub_type = standard_property(18, 20) 

note standard_property() function doesn't need live in class; top-level function too:

>>> def standard_property(startbyte, stopbyte): ...     def getter(self): ...         return decode(self.data[startbyte:stopbyte]) ...     def setter(self, value): ...         self.data[startbyte:stopbyte] = encode(value) ...     return property(getter, setter) ... >>> encode = lambda v: list(v) >>> decode = lambda v: ''.join(v) >>> class packet(object): ...     def __init__(self, data): ...         self.data = data ...     protocol_type = standard_property(16, 18) ...     protocol_sub_type = standard_property(18, 20) ... >>> p = packet(list('foo bar baz spam ham eggs')) >>> p.protocol_type ' h' >>> p.protocol_sub_type 'am' >>> p.protocol_type = '_c' >>> p.protocol_sub_type = 'an' >>> ''.join(p.data) 'foo bar baz spam_can eggs' 

Comments