10

All classes derived from a certain base class have to define an attribute called "path". In the sense of duck typing I could rely upon definition in the subclasses:

class Base:
    pass # no "path" variable here

def Sub(Base):
    def __init__(self):
        self.path = "something/"

Another possiblity would be to use the base class constructor:

class Base:
    def __init__(self, path):
        self.path = path

def Sub(Base):
    def __init__(self):
        super().__init__("something/")

I use Python 3.1.

What would you prefer and why? Is there a better way?

1 Answer 1

14

In Python 3.0+:
I would go with a parameter to the base class's constructor like you have in the second example. As this forces classes which derive from Base to provide the necessary path property, which documents the fact that the class has such a property and that derived classes are required to provide it. Without it, you would be relying on this being stated (and read) somewhere in your class's docstrings, although it certainly does help to also state in the docstring what the particular property means.

In Python 2.6+:
I would use neither of the above; instead I would use:

class Base(object):
    def __init__(self,path):
        self.path=path;

class Sub(Base):
    def __init__(self):
       Base.__init__(self,"something/")

In other words, I would require such a parameter in the base class's constructor, because it documents the fact that all such types will have/use/need that particular parameter and that the parameter needs to be provieded. However, I would not use super() as super is somewhat fragile and dangerous in Python, and I would also make Base a new-style class by inheriting from object (or from some other new-style) class.

Sign up to request clarification or add additional context in comments.

3 Comments

There's nothing fragile about super(). The fragility is in the 2.x syntax, which is fixed in 3.x (which the OP is using, as shown by the super() call), and multiple inheritance in general. There is no reason what so ever to call the baseclass method directly in Python 3.x, the super().__init(...) syntax is never worse and often better.
judging by the use of super, I'd guess that deamon is using py3k
@Thomas Wouters: how would you use super if you all multiple inheritance and base classes with different constructor signatures ? Passing all arguments of derived classes to all base classes looks like a dirty hack, relying on named parameters and let base classes sort out what they need is not much nicer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.