Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #17010 > unrolled thread

Re: Working with Descriptors

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2011-12-11 22:05 -0700
Last post2011-12-11 22:05 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Working with Descriptors Ian Kelly <ian.g.kelly@gmail.com> - 2011-12-11 22:05 -0700

#17010 — Re: Working with Descriptors

FromIan Kelly <ian.g.kelly@gmail.com>
Date2011-12-11 22:05 -0700
SubjectRe: Working with Descriptors
Message-ID<mailman.3529.1323666360.27778.python-list@python.org>
On Sun, Dec 11, 2011 at 9:32 PM, Emeka <emekamicro@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)".

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web