[Tutor] [cleaned-up] Re: problem with a sub-class

Peter Otten __peter__ at web.de
Fri Dec 1 03:35:32 EST 2017


Peter Otten wrote:

Sorry for the mess; second attempt:

A class is an instance of its metaclass.

class A:
    pass

is roughly equivalent to

A = type("A", (), {}) # classname, base classes, class attributes

and

class B(A):
    foo = 42

is roughly equivalent to

B = type(A)("B", (A,), {"foo": 42})

When you subclass from an instance of A instead of A itself this becomes

a = A()
B = type(a)("B", (a,), {"foo": 42})

which can be simplified to

B = A("B", (a,), {"foo": 42})

If this succeeds B is bound to an instance of A, but usually you'll see a 
TypeError, either immediately as the OP, 

>>> class A: pass
... 
>>> class B(A()): pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object() takes no parameters

or later when you try to instantiate B:

>>> class A:
...     def __init__(self, *args):
...         print("__init__{}".format(args))
... 
>>> class B(A()): pass
... 
__init__()
__init__('B', (<__main__.A object at 0x7f3db8a1c048>,), {'__module__': 
'__main__', '__qualname__': 'B'})
>>> isinstance(B, A)                                                                                                                                                                                        
True                                                                                                                                                                                                               
>>> B()                                                                                                                                                                                                            
Traceback (most recent call last):                                                                                                                                                                                 
  File "<stdin>", line 1, in <module>                                                                                                                                                                              
TypeError: 'A' object is not callable                                                                                                                                                                              




More information about the Tutor mailing list