0

I know that it is wrong to do this, but I try to understand what is going on behind the scenes (and if you could potentially duck-type a class for extending it). The code is as follows:

>>> a = 2
>>> class C(a):
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() takes at most 2 arguments (3 given)

I'm trying to understand why int() would be called in this example. It is the type of a but I don't get why that is important here.

WorldSEnder
  • 4,875
  • 2
  • 28
  • 64

2 Answers2

5

You are trying to inherit from an instance object, an integer object. Python treats type(a) as the metatype. The metatype is passed the class name, a tuple of the baseclasses and the body of the class as a dictionary; it is expected to produce the new class object.

In this case, that means type(2)('C', (2,), {}) is called:

>>> type(2)('C', (2,), {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() takes at most 2 arguments (3 given)

Normally, that'd be the type() object itself:

>>> type('C', (object,), {})
<class '__main__.C'>

where I used object as a base class instead.

See What is a metaclass in Python? for everything you didn't want to know about how metaclasses work in Python.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

You are basically doing this:

class C(2):
    pass

As far as I am aware, you cannot inherit from an instance of object in this fashion.

You want to do:

class C(int):
    pass

OR

class C(type(a)):
    pass
taesu
  • 4,482
  • 4
  • 23
  • 41