Zidadi
Zidadi

Reputation: 21

How Zope interface is implemented?

I tried to understand how Zope interface work. I know Interface is just an instance of InterfaceClass which is just an ordinary Class. But if Interface is just a class instance, why it can be used as a base class to be inherited from?

e.g. Class IFoo(Interface): pass

Could you give me some insights? Thank you.

Upvotes: 2

Views: 464

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124748

Python is inherently flexible, and any object can be a base class as long as it looks like a base class. As is always the case with Python, that means implementing some attributes that are expected to be found on a Python classes.

The Interface class (or it's bases Specification and Element) sets several. Look for any variables set starting with a double underscore (__) to gain an understanding:

  • __module__: A string containing the python path module.

  • __name__: The name under which the class was defined.

  • __bases__: The base classes of this class.

  • __doc__: (optional) The docstring of the class.

In addition, the InterfaceClass __init__ method will be called when used as a base class; Python basically treats base classes as metaclasses, and a new instance of the base class's class (metaclass) will be created whenever we use it in a class definition. This means that the __init__ method will be passed the new __name__ and __bases__ values, as well as all the new class attributes as keyword arguments (including __module__ and an optional __doc__).

This is all documented in the Standard type hierarchy section of the Python Data Model document (look for the 'classes' paragraph on special attributes), and in the same document, in the Customizing class creation section (base classes with a __class__ attribute are deemed a type).

So, any python instance that defines at least __module__, __name__ and __bases__ attributes, and a suitable __init__ method will work as a base class for other classes. Python does the rest.

Upvotes: 3

Related Questions