per instance descriptors

Carl Banks pavlovevidence at gmail.com
Thu Dec 7 00:41:59 EST 2006


Simon Bunker wrote:
> Hi I have code similar to this:
>
> class Input(object):
>
>      def __init__(self, val):
>          self.value = val
>
>      def __get__(self, obj, objtype):
>          return self.value
>
>      def __set__(self, obj, val):
>          # do some checking... only accept floats etc
>          self.value = val
>
> class Node(object):
>
> 	a = Input(1)
> 	b = Input(2)
>
> I realise that a and b are now class attributes - however I want to do this:
>
> node1 = Node()
> node2 = Node()
>
> node1.a = 3
> node2.b = 4
>
> And have them keep these values per instance. However now node1.a is 4
> when it should be 3.
[snip]
> Is there any way of doing this nicely in Python?

The easiest way is to store the value in a hidden attribute of the
object.  For instance:

class Input(object):
    def __init__(self,default,name):
        self.default = default
        self.name = name # or, create a name automatically
    def __get__(self,obj,objtype):
        return getattr(obj,self.name,self.default)
    def __set__(self,obj,value):
        setattr(obj,self.name,value)

class Node(object):
    a = Input(1,"_a")
    b = Input(2,"_b")


Carl Banks




More information about the Python-list mailing list