6

I'm using the csv.DictWriter class, and I want to inherit it:

class MyObj(csv.Dictwriter):
    ...

But this type is an old-style object. Can MyObj be a new-style class but still inherit from csv.DictWriter?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
NI6
  • 2,477
  • 5
  • 17
  • 28

2 Answers2

3

Yes, you only have to inherit from object, too:

class MyObj(object, csv.DictWriter):
    def __init__(self, f, *args, **kw):
        csv.DictWriter.__init__(self, f, *args, **kw)
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • And then how the__init__ methood will look? – NI6 Jan 17 '16 at 18:54
  • @NI6: as with any normal class, see answer. – Daniel Jan 17 '16 at 20:28
  • 2
    Hm, this is the opposite order that https://stackoverflow.com/a/11528159/321973 suggests, since your way makes `object`'s methods override `csv.Dictwriter`'s ones. And the very point of using a newstyle class is _not_ explicitly calling a specific parent class' methods but rather being able to use `super()`, isn't it? – Tobias Kienzler Aug 05 '16 at 12:11
  • @TobiasKienzler: `object` and `DictWriter` have no methods in common, so the order is not important. And regarding `super` see http://stackoverflow.com/questions/5066315/why-is-super-broken-in-python-2-x – Daniel Aug 05 '16 at 17:30
  • 2
    @Daniel That is actually what I'd consider a good example for _wrong_ inheritance. As long as no multiple inheritance is used, we're splitting hairs here, but say we subclass `class GrandChild(MyObj, AnotherCSVThing)`, you either have to explicitly call _both_ parents' constructors or let `super` handle it, in which case `MyObj` _not_ using `super` will break the whole MRO mechanism... So TL;DR your answer is not incorrect, but it _may_ lead to difficult-to-debug behaviour in the future... – Tobias Kienzler Aug 08 '16 at 06:46
  • 1
    ...and yes, `DictWriter` does not share any methods with `object`, but in general, even an old-style class might implement e.g. `__str__`, which in this case would be overridden by `object`'s more generic `` – Tobias Kienzler Aug 08 '16 at 06:58
3

As Daniel correctly states, you need to mixin object. However, one major point of using new-style classes is also using super, thus you should use

class MyObj(csv.DictWriter, object):
    def __init__(self, csvfile, mycustomargs, *args, **kwargs):
        super(MyOobj, self).__init__(csvfile, *args, **kwargs)
        ...

As mentioned elsewhere, object should be the last parent, otherwise object's default methods such as __str__ and __repr__ will override the other parent's implementation, which is certainly not what you wanted...

Tobias Kienzler
  • 25,759
  • 22
  • 127
  • 221