Python old style inheritance type in new style class

I am using the csv.DictWriter class and I want to inherit it:

 class MyObj(csv.Dictwriter): ... 

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

+6
source share
2 answers

Yes, you also need to inherit from object :

 class MyObj(object, csv.DictWriter): def __init__(self, f, *args, **kw): csv.DictWriter.__init__(self, f, *args, **kw) 
+3
source

As Daniel said correctly, you need to mix object . However, one of the highlights of using the new style classes also uses super , so 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 must be the last parent, otherwise object default methods, such as __str__ and __repr__ , override another parent element implementation, which, of course, is not what you wanted ...

+2
source

All Articles