Python 2.7.x - problem with obejct.__init__() not accepting *args and **kwargs

Ian Kelly ian.g.kelly at gmail.com
Thu May 16 02:37:53 EDT 2013


On Wed, May 15, 2013 at 8:06 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Wed, 15 May 2013 13:16:09 +0100, Oscar Benjamin wrote:
>
>
>> I don't generally use super()
>
> Then you should, especially in Python 3.
>
> If you're not using super in single-inheritance classes, then you're
> merely making your own code harder to read and write, and unnecessarily
> difficult for others to use with multiple-inheritance.
>
> If you're not using super in multiple-inheritance[1] classes, then your
> code is probably buggy.
>
> There really is no good reason to avoid super in Python 3.

The Python 3 syntactic sugar is the primary reason that I've finally
started using super in single-inheritance classes.  The magicalness of
it still disturbs me a bit, though.

>>> class A:
...     def __str__(self):
...         return super().__str__()
...
>>> class B:
...     __str__ = A.__str__
...
>>> A().__str__
<bound method A.__str__ of <__main__.A object at 0x0289E3B0>>
>>> str(A())
'<__main__.A object at 0x0289E270>'
>>> B().__str__
<bound method B.__str__ of <__main__.B object at 0x0289E470>>

The transplanted __str__ method is considered a method of B by Python...

>>> str(B())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __str__
TypeError: super(type, obj): obj must be an instance or subtype of type

But you can't use it because the super() call is irrevocably tied to
class A.  :-P

Of course the same is true with the syntax "super(A, self)", but at
least with that syntax it is clear that the method is explicitly
referencing class A, and so should not be expected to work correctly
in class B.  By contrast the syntax "super()" looks misleadingly
generic.



More information about the Python-list mailing list