Python: a different constructor trace in a derived class

How can I use another constructor in a derived class in Python?

If I try something like this:

from abc import ABCMeta, abstractproperty, abstractmethod

class AbstractClass(object):
    __metaclass__ = ABCMeta

    def __init__(self):
        pass

and

import AbstractClass

class DerivedClass(AbstractClass):

    _prop = ''
    def __init__(self, param):
        self._prop = param

I get

TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)

I would like to do something like

if (cl_param == '1'):
  obj = DerivedClass1('1', 'c')
else if (cl_param == '2'):
  obj = DerivedClass2('2', 'foo', 2)

etc. The rest of the interface would be the same in every class, they just need different initialization parameters. Or do I need to get around this by specifying options in the list?

+3
source share
3 answers

Make sure you inherit the class, not the module.

I got the same error message when using django models

The mistake was to inherit my model from models. Model

I had something like

class Entry(models):
    content = models.TextField()
    pub_date = models.DateTimeField()

class Entry(models.Model):
    content = models.TextField()
    pub_date = models.DateTimeField()

.

+8
class DerivedClass(AbstractClass):

    _props = ''
    def __init__(self, *params):
        self._props = params
        print params # (1,2,3,4)

c = DerivedClass(1,2,3,4)
+3

Source: https://habr.com/ru/post/1794371/


All Articles