Implementing a circular counter using property / descriptors?
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Sun Oct 8 07:08:20 EDT 2006
On Sun, 08 Oct 2006 12:25:10 +0200, IloChab wrote:
> I'd like to implement an object that represents a circular counter, i.e.
> an integer that returns to zero when it goes over it's maxVal.
[snip]
> The python problem that I give you it's about style.
> I'd like to write in my code something that looks almost like using an
> integer object.
>
> I mean, I'd like to write:
>
> cnt = CircularConter(maxVal=100, initialVal=10)
> cnt += 100 # cnt value is 9
> print cnt # prints 9
> 100 > cnt # is false
All this is perfectly sensible.
> cnt = 100 # cnt new value is 100 [NOT rebind cnt with 100]
This is not possible. Names like cnt are just labels, they don't have
behaviour. Objects have behaviour; but objects don't and can't know what
name or names they are assigned to.
[snip]
> The fact is that I don't like to write cnt.set(100) or
> cnt = CircularConter(100, 100) instead of cnt = 100.
How do you expect the Python compiler to know you want a CircularConter
instance if you just write 100?
(By the way, in English, the correct spelling is counter, not conter.)
> So I thought that property or descriptors could be useful.
> I was even glad to write:
>
> cnt = CircularConterWithProperty(maxVal=100, initialVal=10)
> cnt.val += 100
> print cnt.val
> 100 > cnt.val # is false
> cnt.val = 100
>
> just to give uniformity to counter accessing syntax.
> But I wasn't able to implement nothing working with my __cmp__ method.
__cmp__ is for CoMParisons, not binding names to objects.
--
Steven.
More information about the Python-list
mailing list