Quick question about Python(ic) inheritence: what is the difference between the idiom posted here (super(ChildClass,self).method(args)) vs. the one on the Python docs site (ParentClass.method(self,[args]))? Is one more Pythonic than the other?
1 Answer
Using super(ChildClass, self).method(args) allows you to walk the method resolution order and -- if everyone but the last parent uses super -- call every class in the hierarchy exactly once. (Not that super only works with new-style classes.)
Using ParentClass.method(self, args) calls one specific class. It does not work when involved in multiple inheritance.
This article provides some description of the issue and clarifies a lot of issues for some people. I don't agree with all of its conclusions, but it provides good examples and discussion.
7 Comments
Mike Graham
Dealing with
__init__ is precarious because of a few reasons: 1) __init__'s signature becomes the constructor's signature, and constructors are the one area where the theory says vastly different signatures are completely kosher. 2) There are gazillions of __init__s out there already that do this wrong already. 3) Some details of __init__ have been fiddled with multiple times in recent years. It's often better—though possibly not as useful—to think about how super works with methods other than __init__, where the situation is more straightforward.Mike Graham
Personally, I avoid inheritance the vast majority of the time, which avoids much of this nastiness. The times I do tend to use it—for mixins and for registering some defined set of callbacks—don't really require this sort of thing.
Voo
I assume you meant "multiple inheritance" above in which case I agree. But if I write a class that may be inherited, I'd prefer if my init function wouldn't make it unusable for that usecase if I can avoid it. Sure in other situations it's simpler, but if I can't use super in my "constructor" (which is where I need this functionality the most often I think), that means I may have to use two different methods to do the same in one class - that's also not great.
Mike Graham
@Voo, Nope, I mean inheritance.
|