I have this code:
class main():
params = {}
class a(main):
def __init__(self):
self.params['test'] = "111aa"
print self.params
class b(main):
def __init__(self):
self.params['be'] = "222bbb"
print self.params
a()
#{'test': '111aa'}
b()
#{'test': '111aa', 'be': '222bbb'}
I need from b to print only {'be': '222bbb'}
Is there any way how to do it ?
Thanks
asked Aug 20, 2013 at 21:51
Peter
6191 gold badge8 silver badges15 bronze badges
1 Answer 1
Try this:
class main(object): # use new-style classes!
def __init__(self):
self.params = {}
class a(main):
def __init__(self):
super(a, self).__init__()
self.params['test'] = "111aa"
print self.params
class b(main):
def __init__(self):
super(b, self).__init__()
self.params['be'] = "222bbb"
print self.params
Notice that in your code params was defined as a class attribute. By defining it in __init__ of the superclass, we're stating that it's an instance attribute. Also notice that the subclasses call __init__ on the superclass.
In this way, we're making sure that each instance has its own params attribute, without sharing it. You can't expect to share an object between instances and have each one with different values for it, it's a contradiction.
answered Aug 20, 2013 at 21:55
Óscar López
237k38 gold badges321 silver badges391 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Blckknght
This is a good answer and a good explanation of the issue. My only suggestion would be to use
super() to call main's __init__ method, rather than naming the super class explicitly. That's because super supports multiple inheritance, which is difficult or impossible otherwise.lang-py
paramsis a class attribute. You want an instance attribute. Setself.paramsinmain.__init__, and remember to invoke the superclass constructor in the subclass constructors.paramsbetween subclasses ofmain?paramsbetween the subclasses, but not have each subclass update the sameparams? This is a very confusing notion of "share" you have....class main():isn't illegal, but it will raise red flags to anyone who reads it. If you really want a classic class for some reason, the idiomatic way to write that isclass main:. If you don't have any idea what that last sentence meant, you don't want a classic class; writeclass main(object):.mainat all seems pretty bad form, in my book. It's not actually wrong, but other uses ofmainare sufficiently well-known and popular as to make it pretty confusing, and potentially troublesome if you ever inadvertently use this class in a program that really does have amainfunction.