python - Passing parameter to base class constructor or using instance variable? -


all classes derived base class have define attribute called "path". in sense of duck typing rely upon definition in subclasses:

class base:     pass # no "path" variable here  def sub(base):     def __init__(self):         self.path = "something/" 

another possiblity use 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 prefer , why? there better way?

in python 3.0+:
go parameter base class's constructor have in second example. forces classes derive base provide necessary path property, documents fact class has such property , derived classes required provide it. without it, relying on being stated (and read) somewhere in class's docstrings, although state in docstring particular property means.

in python 2.6+:
use neither of above; instead use:

class base(object):     def __init__(self,path):         self.path=path;  class sub(base):     def __init__(self):        base.__init__(self,"something/") 

in other words, require such parameter in base class's constructor, because documents fact such types have/use/need particular parameter , parameter needs provieded. however, not use super() super fragile , dangerous in python, , make base new-style class inheriting object (or other new-style) class.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -