Need help with Python scoping rules
Ulrich Eckhardt
eckhardt at satorlaser.com
Wed Aug 26 05:04:43 EDT 2009
Ulrich Eckhardt wrote:
> Jean-Michel Pichavant wrote:
>> class Color:
>> def __init__(self, r, g,b):
>> pass
>> BLACK = Color(0,0,0)
>>
>> It make sens from a design point of view to put BLACK in the Color
>> namespace. But I don't think it's possible with python.
>
> class Color:
> ...
>
> setattrib(Color, "BLACK", Color(0,0,0))
Apart from it being "setattr" and not "setattrib", a simple
Color.BLACK = Color(0,0,0)
should have done the job here. However, what I had in mind was this:
class Color:
_colors = [ ("BLACK", (0,0,0)),
("WHITE", (1,1,1))
]
def __str__(self):
# try to locate a name
for name, rgb in Color._colors:
if self.rgb==rgb:
return name
# no name found, just format as a triplet
return "(%s, %s, %s)" % self.rgb
# add symbolic names
for name, rgb in Color._colors:
setattr(Colors, name, Color(rgb))
...which I got as suggestion on my question how to model C enumeration
lookalikes.
Uli
--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
More information about the Python-list
mailing list