Best way to do attribute docstrings?
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Wed Sep 26 01:25:54 EDT 2007
En Tue, 25 Sep 2007 22:41:31 -0300, Ken Kuhlman <kskuhlman at gmail.com>
escribi�:
> Replying to myself in case someone finds this interesting.
>
> Anyway, I took another shot at this with a little fresher mind, and it
> was quickly obvious that I was trying to force attributes to behave
> more like classes. It was a small step from there to creating a
> factory function to return instances of the appropriate class. I'm
> much happier with the result than either of the two previously posted
> kludges.
Still there is something I don't understand on your design. You appear to
be always concerned about *class* attributes. *Instance* attributes are
far more comon, and usually they change their value many times.
> class Animal(object):
> four_legs = attr(value = True, doc = "Animal has four legs")
> favorite_food = attr('cheese', doc = "Animal's favorite food")
> has_fur = attr(False)
> has_fur.__doc__ "Animal has fur"
As an example, how would you annotate attributes on a hierarchy like this?
class Animal(object):
can_fly = False # no Animal can fly unless explicitely noted
lives = 1 # most Animals have a single life
def __init__(self, color, legs, favorite_food):
self.color = color
self.legs = legs
self.favorite_food = favorite_food
class Mammal(Animal):
pass
class Cat(Mammal):
def __init__(self, color):
Mammal.__init__(self, color=color, legs=4, favorite_food='mice')
self.lives = 7 # a cat starts with 7 lives
class Mouse(Mammal):
def __init__(self, color, personality):
Mammal.__init__(self, color=color, legs=4, favorite_food='cheese')
self.personality = personality
class Bird(Animal):
can_fly = True
def __init__(self, color):
Animal.__init__(self, color=color, legs=2, favorite_food='seed')
tweety = Bird('yellow')
sylvester = Cat('black')
tom = Cat('blue')
jerry = Mouse('brown', 'nice')
itchy = Mouse('blue', 'sadist')
scratchy = Cat('black')
scratchy.lives = 7**7 # or so...
print tweety.legs
print scratchy.color
print scratchy.lives
--
Gabriel Genellina
More information about the Python-list
mailing list