views:

189

answers:

1

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  A: 

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.

Michael Aaron Safyan
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.
Thomas Wouters
judging by the use of `super`, I'd guess that deamon is using py3k
SilentGhost