Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inheritance old style type in a new style class

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?

like image 923
NI6 Avatar asked Jan 17 '16 18:01

NI6


People also ask

What is the difference between old style and new style classes in Python?

Object model details Another difference is in the behavior of arithmetic operations: in old-style classes, operators like + or % generally coerced both operands to the same type. In new-style classes, instead of coercion, several special methods (e.g. __add__ / __radd__ ) may be tried to arrive at the result.

What is __ new __ in Python?

__new__ is static class method, while __init__ is instance method. __new__ has to create the instance first, so __init__ can initialize it. Note that __init__ takes self as parameter. Until you create instance there is no self . Now, I gather, that you're trying to implement singleton pattern in Python.

What is self __ dict __ Python?

__dict__ is A dictionary or other mapping object used to store an object's (writable) attributes. Or speaking in simple words every object in python has an attribute which is denoted by __dict__. And this object contains all attributes defined for the object.

Does Python 2 have classes?

Compared with other programming languages, Python's class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++ and Modula-3.


2 Answers

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)
like image 95
Daniel Avatar answered Oct 22 '22 01:10

Daniel


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...

like image 20
Tobias Kienzler Avatar answered Oct 22 '22 00:10

Tobias Kienzler