On Sun, Dec 11, 2011 at 9:32 PM, Emeka <emekami...@gmail.com> wrote: > > Hello All, > > How do I get the __set__ to work here? > > import random > > class Die(object): > def __init__(self, sides=6): > self.sides = sides > > def __get__(self, instance, owner): > return int(random.random() * self.sides) + 1 > > def __set__(self, instance, value): > instance.__dict__[self.side] = value > > > > class Game(object): > d6 = Die() > d10 = Die(sides=10) > d20 = Die(sides=20) > > > Game.d3 = 90 (This failed)
I'm not sure exactly what it is you're trying to do with this, but there are a couple problems. First of all, at "Game.d3 = 90" you appear to be trying to set the value of a descriptor on a class object. This doesn't work, because __set__ doesn't get called when you try to set the descriptor on the class object directly. It only reassigns the attribute and replaces the descriptor. You need to either create an instance of Game and use the descriptors on that, or put the descriptor in a metaclass. Second, you're assigning to the d3 descriptor, but you never created a descriptor for the d3 attribute. The only descriptors on the Game class are d6, d10, and d20. If you're trying to assign to the descriptor, it would need to exist first. If you're trying to add a new descriptor, you would need to do something like "Game.d3 = Die(sides=3)". -- http://mail.python.org/mailman/listinfo/python-list