So, I have this class which keeps track of the number of instances that are created:
class Base(object):
total = 0
def __init__(self):
<more code>
Base.total += 1
Now, I want to create a derived class, but I don't want its instances to add to the total in Base. So I subtract in order to undo the adding:
class Derived(Base):
def __init__(self):
super(Derived,self).__init__()
Base.total -= 1
It works, however, it does not seem to me a good practice to access a base class attribute in the derived class. Is there a better method?
asked Apr 13, 2016 at 12:25
fdireito
1,7691 gold badge14 silver badges19 bronze badges
1 Answer 1
You can avoid calling superclass constructor in child class. It works fine but not looking very nice
noinspection PyMissingConstructor
class Derived(Base):
def __init__(self):
<more code>
answered Apr 13, 2016 at 12:51
dfostic
1,7561 gold badge15 silver badges8 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
__init__method of your base class. You can always move your<more code>block into a separate function.