Class property
Steven Bethard
steven.bethard at gmail.com
Tue Oct 11 16:41:37 EDT 2005
Laszlo Zsolt Nagy wrote:
> class A(object):
> cnt = 0
> a_cnt = 0
> def __init__(self):
> A.cnt += 1
> if self.__class__ is A:
> A.a_cnt += 1
> class B(A):
> pass
> print A.cnt,A.a_cnt # 0,0
> b = B()
> print A.cnt,A.a_cnt # 1,0
> a = A()
> print A.cnt,A.a_cnt # 2,1
>
> But then, I may want to create read-only class property that returns the
> cnt/a_cnt ratio.
> This now cannot be implemented with a metaclass, because the metaclass
> cannot operate on the class attributes:
Huh? Every function in the metaclass takes the class object as the
first parameter. So they can all operate on the class attributes:
py> class A(object):
... cnt = 0
... a_cnt = 0
... def __init__(self):
... A.cnt += 1
... if self.__class__ is A:
... A.a_cnt += 1
... class __metaclass__(type):
... @property
... def ratio(cls):
... return cls.a_cnt/float(cls.cnt)
...
py> class B(A):
... pass
...
py> A.cnt, A.a_cnt
(0, 0)
py> A.ratio
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 11, in ratio
ZeroDivisionError: float division
py> b = B()
py> A.cnt, A.a_cnt, A.ratio
(1, 0, 0.0)
py> a = A()
py> A.cnt, A.a_cnt, A.ratio
(2, 1, 0.5)
STeVe
More information about the Python-list
mailing list