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
?
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.
__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.
__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.
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.
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)
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With