【问题标题】:How to pass parameters to parent class with type() in python?如何在python中使用type()将参数传递给父类?
【发布时间】:2014-04-28 20:14:38
【问题描述】:
class Parent(object):

    def __init__(self, first):
        self.first = first

class Child1(Parent):

    def __init__(self):
        Parent.__init__(self, 'A')
  • 我有这个父类,我想创建 12 个类似的继承父类的类,它们都具有相同的签名和无参数。如何使用type() 定义 Child1? 到目前为止我有 Child1 = type('Child1', (Rank,), dict()) 但我怎样才能将 first 传递给 Parent 类?

【问题讨论】:

    标签: python class inheritance types parameters


    【解决方案1】:

    您使用属性字典。我认为这样的事情应该可以解决问题。

    def genericInit(self):
        Parent.__init__(self, 'A')
    
    type('Child1', (Rank,), {'__init__': genericInit})
    

    按 cmets 更新: 你可以使用functools.partial

    attrDict = {'init': functools.partial(Parent.__init__, first='A')}
    

    但这是糟糕的代码。您通常不想从 init 以外的任何地方调用 init,因为这会让使用您的课程的任何人感到困惑。

    【讨论】:

    • Child1 = type('Child1', (Parent,), {'init' : Parent.__init__('A')}) 我想做这样的事情,但这不起作用?
    • 这失败了,因为您需要将Parent 的实例传递给Parentinit 方法。你试图在类型实例化时调用它,但你需要在实例化类时调用它。为什么以上不起作用?
    • 我必须创建超过 10 个子类,我不想为每个子类都创建 genericInt。
    猜你喜欢
    • 2013-11-09
    • 2016-10-07
    • 2021-09-11
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    相关资源
    最近更新 更多