Python: Different constructor footprint in derived class
How can I have a different 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)
and so on. The rest of the interface would be similar in each class, they just need different initialisation parameters. Or do I have to circumvent this by giving the parameters in a list?
Ensure you inherit from a class, not a module.
I got the same error message when using django models
The mistake was in inheriting my model from models.Model
I had something like
class Entry(models):
content = models.TextField()
pub_date = models.DateTimeField()
when it should have been
class Entry(models.Model):
content = models.TextField()
pub_date = models.DateTimeField()
Note the missing models.Model
Python tutorial, §4.7.3, "Arbitrary Argument Lists"
class DerivedClass(AbstractClass):
_props = ''
def __init__(self, *params):
self._props = params
print params # (1,2,3,4)
c = DerivedClass(1,2,3,4)
精彩评论