1 | # -*- Mode: Python; tab-width: 4 -*- |
||
2 | |||
3 | # It is tempting to add an __int__ method to this class, but it's not |
||
4 | # a good idea. This class tries to gracefully handle integer |
||
5 | # overflow, and to hide this detail from both the programmer and the |
||
6 | # user. Note that the __str__ method can be relied on for printing out |
||
7 | # the value of a counter: |
||
8 | # |
||
9 | # >>> print 'Total Client: %s' % self.total_clients |
||
10 | # |
||
11 | # If you need to do arithmetic with the value, then use the 'as_long' |
||
12 | # method, the use of long arithmetic is a reminder that the counter |
||
13 | # will overflow. |
||
14 | |||
15 | class counter: |
||
16 | "general-purpose counter" |
||
17 | |||
18 | def __init__ (self, initial_value=0): |
||
19 | self.value = initial_value |
||
20 | |||
21 | def increment (self, delta=1): |
||
22 | result = self.value |
||
23 | try: |
||
24 | self.value = self.value + delta |
||
25 | except OverflowError: |
||
26 | self.value = long(self.value) + delta |
||
27 | return result |
||
28 | |||
29 | def decrement (self, delta=1): |
||
30 | result = self.value |
||
31 | try: |
||
32 | self.value = self.value - delta |
||
33 | except OverflowError: |
||
34 | self.value = long(self.value) - delta |
||
35 | return result |
||
36 | |||
37 | def as_long (self): |
||
38 | return long(self.value) |
||
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
![]() |
|||
39 | |||
40 | def __nonzero__ (self): |
||
41 | return self.value != 0 |
||
42 | |||
43 | def __repr__ (self): |
||
44 | return '<counter value=%s at %x>' % (self.value, id(self)) |
||
45 | |||
46 | def __str__ (self): |
||
47 | return str(long(self.value)) |
||
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
|
|||
48 |