Could not make fun of __subclasses__ in python

Why is the following code not working?

>>> from mock import *
>>> class A(object):
...     pass
...
>>> mock = create_autospec(A)
>>> mock.foo = Mock()                # this works
>>> mock.__bar__ = Mock()            # this works too
>>> mock.__subclasses__ = Mock()     # this fails
AttributeError: Mock object has no attribute '__subclasses__'

I think I follow the documentation of mocking magic methods. The docs really notice that trying to trick a magic method that is not part of the specification will not work. But why was __subclasses__n’t the specification of the auto-specifying class a new style?

+4
source share
2 answers

__subclasses__not included in class specification. It is part of the class metatype ( typehere).

Python always , . Python __subclasses__, , type(classobj).__subclasses__(classobj) . , __subclasses__ .

, ; Mock __add__ __str__ create_autospec(), , Python type(mockinstance).__str__(mockinstance) __str__.

classobj.__subclasses__() , mock, ; , .

Mocks , - :

>>> m = create_autospec(A)
>>> m.__add__ = Mock()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/site-packages/mock.py", line 767, in __setattr__
    raise AttributeError("Mock object has no attribute '%s'" % name)
AttributeError: Mock object has no attribute '__add__'

:

>>> m.__dummy__ = Mock()
>>> m.__dummy__
<Mock name='mock.__dummy__' id='4427608656'>

A, __subclass__, :

>>> class AMockSpec(A):
...     def __subclasses__(self): pass
...
>>> m = create_autospec(AMockSpec)
>>> m.__subclasses__ = Mock()
>>> m.__subclasses__.return_value = ['SomeMockValue']
>>> m.__subclasses__()
['SomeMockValue']
+1

(__subclasses__ __class__):

>>> from mock import *
>>> class A(object):
...     pass
...
>>> m = create_autospec(A)
>>> m.__class__.__subclasses__()
[]
>>> class B(A): pass
...
>>> m.__class__.__subclasses__()
[<class '__main__.B'>]
>>> m.__class__.__subclasses__ = Mock()
>>> m.__class__.__subclasses__()
<Mock name='mock()' id='4372594896'>
0

All Articles