hkk
hkk

Reputation: 2149

How to initialize object from class passed as parameter

I am trying to send a class, as an argument, to a function, then create an object of that class within the function, and use that object. However, my attempts resulted in errors.

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

The first attempt yielded this error: AttributeError: Table instance has no __call__ method and the second resulted in this: TypeError: unbound method __init__() must be called with Table instance as first argument (got int instance instead).

What is the correct way to do this?

Upvotes: 1

Views: 151

Answers (1)

logc
logc

Reputation: 3923

The first error is telling you that you are passing an instance of the class, and not the class itself, as an argument to your function! That is why Python is interpreting

x = some_class()

as a call to the instance, and not as an instantiation (creation) of the class.

And here is an example of how what you want to do actually works:

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

I think (but I am guessing here) you have done something along the lines of:

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

Do not create a_table, just pass Table to your function.

Upvotes: 3

Related Questions