class variables for subclasses tuple
alainpoint at yahoo.fr
alainpoint at yahoo.fr
Wed Mar 8 05:06:40 EST 2006
Peter Otten wrote:
> alainpoint at yahoo.fr wrote:
>
> > Point.x=0 leads to having p.x==0
> > It seems not possible to have class variables and instance variable
> > having the same name and yet different values.
>
> A quick check:
>
> >>> class T(tuple):
> ... class __metaclass__(type):
> ... x = property(lambda cls: 0)
> ... x = property(lambda self: self[0])
> ...
> >>> t = T("abc")
> >>> t.x
> 'a'
> >>> T.x
> 0
>
> So possible it is. Come back if you're stuck generalizing the above.
>
> Peter
Thanks for your magic answer.
But i am not so good at magic ;-)
If i want to generalize to a arbitrary number of variables, i got
syntax errors.
Within a class, you can only method/class definitions and assignments.
It is therefore difficult to do something like:
for idx, attr_name in enumerate(attribute_names):
setattr(__metaclass__,attr_name, property(lambda cls:idx)
for idx, attr_name in enumerate(attribute_names):
setattr(T,attr_name, property(lambda self:self[idx])
Alain
More information about the Python-list
mailing list