OOP in Python
Chris Barker
chrishbarker at home.net
Wed Jun 20 17:00:42 EDT 2001
Alex Martelli wrote:
> A class may have attributes (it's also possible to use a module
> attribute, aka 'global variable', of course). Example:
>
> class Totalizer:
> grand_total = 0
> def inc(self):
> self.__class__.grand_total += 1
> def dec(self):
> self.__class__.grand_total -= 1
> def __str__(self):
> return "Total is %d"%self.__class__.grand_total
Or make the class attribute a mutable type, and the syntax gets simpler:
class Totalizer:
grand_total = [0]
def inc(self):
self.grand_total[0] += 1
def dec(self):
self.grand_total[0] -= 1
def __str__(self):
return "Total is %d"%self.grand_total[0]
# two separate instances
one = Totalizer()
two = Totalizer()
# but they share state! Try:
one.inc()
two.inc()
one.inc()
two.inc()
print one
Nice trick, though, Alex, I hadn't yet discovered that one.
-Chris
--
Christopher Barker,
Ph.D.
ChrisHBarker at home.net --- --- ---
http://members.home.net/barkerlohmann ---@@ -----@@ -----@@
------@@@ ------@@@ ------@@@
Oil Spill Modeling ------ @ ------ @ ------ @
Water Resources Engineering ------- --------- --------
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------
More information about the Python-list
mailing list