Page 1 of 1

derived class from socket

Posted: Sun Apr 28, 2019 5:16 pm
by chastings
It seems I can't derive from socket, and I can't figure out why.

First, a simple inheritance example with my own classes in micropython as a sanity check:

>>> class base:
... def foo(self):
... print( "foo" )
...
>>> class derived(base):
... pass
...
>>> d=derived()
>>> d
<derived object at 3fff1c90>
>>> d.foo()
foo

Now, the same example with socket...

>>> import socket
>>> class dsocket(socket.socket):
... pass
...
>>> d=dsocket()
>>> d
<socket state=0 timeout=-1 incoming=0 off=0>
>>> s=socket.socket()
>>> s
<socket state=0 timeout=-1 incoming=0 off=0>

The derived object seems to have the same type as an object of the base class, which is unexpected.

Anyone know what's going on here? Happens in both releases 1.9.4 and 1.10. Thanks!

Re: derived class from socket

Posted: Mon Apr 29, 2019 5:52 am
by kevinkk525
Subclassing built-ins can sometimes work - but it's best avoided as behaviour is not guaranteed.
Doesn't work for machine.Pin either.

Re: derived class from socket

Posted: Mon Apr 29, 2019 6:28 am
by pythoncoder
It's worth reading this doc which explains the differences between MicroPython and CPython.

The problem with subclassing buiiltins can usually be worked around by using composition rather than inheritance.