1#!/usr/bin/env python
2# This is a doctest
3"""
4=========================================
5Subclassing Objective-C classes in Python
6=========================================
7
8It is possible to subclass any existing Objective-C class in python.
9
10We start by importing the interface to the Objective-C runtime, although
11you'd normally use wrappers for the various frameworks, and then locate
12the class we'd like to subclass::
13
14    >>> import objc
15    >>> NSEnumerator = objc.lookUpClass('NSEnumerator')
16    >>> NSEnumerator
17    <objective-c class NSEnumerator at 0xa0a039a8>
18
19You can then define a subclass of this class using the usual syntax::
20
21    >>> class MyEnumerator (NSEnumerator):
22    ...    __slots__ = ('cnt',)
23    ...    #
24    ...    # Start of the method definitions:
25    ...    def init(self):
26    ...        self.cnt = 10
27    ...        return self
28    ...    #
29    ...    def nextObject(self):
30    ...        if self.cnt == 0:
31    ...            return None
32    ...        self.cnt -= 1
33    ...        return self.cnt
34    ...    #
35    ...    def __del__(self):
36    ...        global DEALLOC_COUNT
37    ...        DEALLOC_COUNT = DEALLOC_COUNT + 1
38
39
40To check that our instances our deallocated we maintain a ``DEALLOC_COUNT``::
41
42    >>> DEALLOC_COUNT=0
43
44As always, the creation of instances of Objective-C classes looks a bit odd
45for Python programs:
46
47    >>> obj = MyEnumerator.alloc().init()
48    >>> obj.allObjects()
49    (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
50
51Destroy our reference to the object, to check if it will be deallocated::
52
53   >>> del obj
54   >>> DEALLOC_COUNT
55   1
56
57"""
58import doctest
59import __main__
60doctest.testmod(__main__, verbose=1)
61