cniehaus (cniehaus) wrote,

Python class variables and code dupclication

Hello

I am having a Python problem. I have two classes, both inheriting the class 'Animal'. I want a counter, that means Animal.count_of() should return the number of objects.

Please have a look at this code:


class Animal(object):
    number = 0
   
    def __init__(self):
        Animal.number += 1
       
    def __del__(self):
        Animal.number -= 1
       
    def count_of(self):
        print Animal.number
       
class Laus(Animal):
    def __init__(self):
        Animal.__init__(self)
   
class Bug(Animal):
    def __init__(self):
        Animal.__init__(self)

   
l1 = Laus()
l1.count_of()
l2 = Laus()
l1.count_of()
l3 = Laus()
l1.count_of()
l4 = Laus()
l1.count_of()

b1 = Bug()
b1.count_of()



This is not working because both classes are using the same class variable (number) which means the number in the last line is 5, not 1. I could obviously have one class variable for Bug and one for Laus, but that would mean I'd have to have two .count_of()-methods as well (and more would have to be duplicated, I only pasted a stripped down code).

Is there a trick to have one base-class Animal with a counter or do I really have to do everything twice?

  • Post a new comment

    Error

    default userpic

    Your reply will be screened

  • 31 comments