per instance descriptors

George Sakkis george.sakkis at gmail.com
Wed Dec 6 23:58:01 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
> node.b = 4
>
> And have them keep these values per instance. However now node1.a is 4
> when it should be 3.
>
> Basically I want to have the Input class as a gateway that does lots of
> checking when the attibute is assigned or read.
>
> I have had a look at __getattribute__(), but this gets very ugly as I
> have to check if the attribute is an Input class or not.
>
> Also I don't think property() is appropriate is it? All of the
> attributes will essentially be doing the same thing - they should not
> have individual set/get commands.
>
> Is there any way of doing this nicely in Python?

What about __setattr__ ? At least from your example, checking happens
only when you set an attribute. If not, post a more representative
sample of what you're trying to do.

George




More information about the Python-list mailing list