per instance descriptors

Simon Bunker simon at renderIHATESPAMmania.com
Thu Dec 7 18:27:01 EST 2006


Carl Banks wrote:
> 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
> 

This does seem the easiest way - but also a bit of a hack. Would it work 
to assign to instance variables - each the class attribute sets the 
instance attribute with the same name? Or would that not work?

Simon



More information about the Python-list mailing list