【问题标题】:How to initialize object from class passed as parameter如何从作为参数传递的类中初始化对象
【发布时间】:2014-12-25 18:21:07
【问题描述】:

我试图将一个类作为参数发送给一个函数,然后在函数中创建该类的一个对象,并使用该对象。但是,我的尝试导致了错误。

def test(some_class):
    x = some_class() # first attempt
    x = some_class.__init__() # second attempt

第一次尝试产生了这个错误:AttributeError: Table instance has no __call__ method,第二次产生了这个错误: TypeError: unbound method __init__() must be called with Table instance as first argument (got int instance instead).

这样做的正确方法是什么?

【问题讨论】:

    标签: python function class oop object


    【解决方案1】:

    第一个错误是告诉你你正在传递一个类的实例,而不是类本身,作为你的函数的参数!这就是 Python 解释的原因

    x = some_class()
    

    作为对实例的调用,而不是作为类的实例化(创建)。

    下面是一个示例,说明您想要做什么实际上是如何工作的:

    In [1]: class Table(object):
       ...:     def __init__(self, number):
       ...:         self.number = number
       ...:
    
    In [2]: def test(some_table):
       ...:     x = some_table(5)
       ...:     return x.number == 5
       ...:
    
    In [3]: test(Table)
    Out[3]: True
    

    我认为(但我在这里猜测)你做了一些类似的事情:

    In [5]: a_table = Table(10)
    
    In [6]: test(a_table)
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-6-c3b83a3a3118> in <module>()
    ----> 1 test(a_table)
    
    <ipython-input-2-01a30f6ba7b1> in test(some_table)
          1 def test(some_table):
    ----> 2     x = some_table(5)
          3     return x.number == 5
          4
    
    TypeError: 'Table' object is not callable
    

    不要创建a_table,只需将Table 传递给您的函数。

    【讨论】:

    • 感谢您的及时答复。这解决了它。
    • 总是乐于提供帮助 :) 如果它解决了问题,您介意接受答案吗?它向其他人表明该解决方案有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 2022-07-10
    • 1970-01-01
    相关资源
    最近更新 更多