Python:派生类中不同的构造函数足迹
如何在 Python 的派生类中拥有不同的构造函数?
如果我尝试这样的事情:
from abc import ABCMeta, abstractproperty, abstractmethod
class AbstractClass(object):
__metaclass__ = ABCMeta
def __init__(self):
pass
我
import AbstractClass
class DerivedClass(AbstractClass):
_prop = ''
def __init__(self, param):
self._prop = param
得到
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
我想做类似的事情
if (cl_param == '1'):
obj = DerivedClass1('1', 'c')
else if (cl_param == '2'):
obj = DerivedClass2('2', 'foo', 2)
等等。每个类中接口的其余部分都是相似的,它们只是需要不同的初始化参数。或者我是否必须通过在列表中给出参数来规避这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确保您从类而不是模块继承。
使用 django models 时,我收到了相同的错误消息
错误在于从 models.Model 继承我的模型,
我有类似的内容
,应该
注意缺少的 models.Model
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
when it should have been
Note the missing models.Model
Python 教程,第 4.7.3 节,“任意参数列表”
Python tutorial, §4.7.3, "Arbitrary Argument Lists"