Properties and Objects...

Peter Otten __peter__ at web.de
Mon Sep 24 06:07:15 EDT 2007


George V. Neville-Neil wrote:

> I have been trying to switch this over to using properties, which seem
> at first glance to be cleaner, but which I am having a lot of problems
> with.  In particular I want to add a property to an object, not a
> class.  

You can't. The underlying mechanism (descriptors) works on the class level.

> The field list in a class is actually relatively static but I
> wind up with ugly code like:
> 
> class ethernet(pcs.Packet):
>     """Ethernet"""
>     __layout__ = pcs.Layout()
>     _map = ethernet_map.map
>     
>     src = pcs.StringField("src", 48)
>     dst = pcs.StringField("dst", 48)
>     type = pcs.Field("type", 16)

>From the piece of code you present I would guess that the above class
attributes are superfluous. Or doesn't pcs.Packet.__init__() do the

self.src = ... 

thingy?

>     def __init__(self, bytes = None, timestamp = None):
>         """initialize an ethernet packet"""
> 
>         src = pcs.StringField("src", 48)
>         dst = pcs.StringField("dst", 48)
>         type = pcs.Field("type", 16)
> 
>         pcs.Packet.__init__(self, [dst, src, type], bytes = bytes)
>         self.description = inspect.getdoc(self)
> 
> and assigning the properties at class time means that it's hard to have
> variations, packets with the same name but with slightly varying field
> lists.

What's so hard about subclassing?

> So, is there a way to assign a property to an object, like this:
> 
>     def __init__(....
>          self.src = property()
> 
> or something like that?

You can make a property that delegates its behaviour, e. g:

import new

def get_src_one(self):
    return 42

class A(object):
    src = property(lambda self: self.get_src())
    def __init__(self, get):
        self.get_src = new.instancemethod(get, self)

a = A(get_src_one)
print a.src

But -- ceterum censeo -- subclassing is probably better, cleaner and
faster. Then instead of calling the class directly make a factory function
that picks the appropriate subclass.

Peter



More information about the Python-list mailing list