A couple questions about classes and inheritance
Christian Heimes
lists at cheimes.de
Sun May 16 19:17:19 EDT 2010
> First, I've looked a fair bit and can't find how one can find the base
> classes of a subclass? isinstance and issubclass sort of do the
> opposite of what I want. Surely somewhere there is something like
>
> MyThingee.something.orOther.baseClasses()
You can get the direct parents of a class with the attribute __bases__.
The class attribute __mro__ returns a tuple of for the method resolution
order. But instead of poking around yourself I suggest you use the
inspect module. It provides a high level interface.
>>> class Example:
... pass
...
>>> Example.__bases__
(<class 'object'>,)
>>> Example.__mro__
(<class '__main__.Example'>, <class 'object'>)
> But what happens if I try to subclass function?
>
> First attempt:
>>>>
>>>> class MyFunction(function):
> .... pass
> ....
> Traceback (most recent call last):
> File "<stdin>", line 1, in<module>
> NameError: name 'function' is not defined
There is no object called function in the list of builtins. You can't
subclass from function anyway so there is no point in accessing the
function object. If you want to create some callable class you have to
provide a method call "__call__". It's called when you call the
instances of your class like a function.
>>> def a():
... pass
...
>>> type(a)
<class 'function'>
>>> function = type(a)
>>> class MyFunc(function):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type 'function' is not an acceptable base type
> Anyway, again can you point me to somewhere that I can learn more? In
> particular, is there a list somewhere of the builtin types that are
> not subclassable?
I don't think it's documented anyway. You have to try yourself. In
general you don't have to subclass builtin types. Some classes are
tricky to subclass like e.g. immutable classes (str, bytes) or dict.
Christian
More information about the Python-list
mailing list