Python:派生类中不同的构造函数足迹

发布于 2024-10-19 12:39:24 字数 771 浏览 5 评论 0原文

如何在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

辞慾 2024-10-26 12:39:24

确保您从类而不是模块继承。

使用 django models 时,我收到了相同的错误消息

错误在于从 models.Model 继承我的模型,

我有类似的内容

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

,应该

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

注意缺少的 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

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

ま昔日黯然 2024-10-26 12:39:24
class DerivedClass(AbstractClass):

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

c = DerivedClass(1,2,3,4)
class DerivedClass(AbstractClass):

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

c = DerivedClass(1,2,3,4)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文