On May 16, 4:17 pm, Christian Heimes <li...@cheimes.de> wrote:
> > 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.


It's not a list, but you can tell if a given type is subclassable by
testing bit 10 of the __flags__ attribute:

type(lambda:0).__flags__ & 1024  ->  0
int.__flags__ & 1024  ->  1024


The reason some types are not subclassable is simply because there's
more involved to write a type at the C level that's subclassable.  For
a lot of types the work wasn't considered worth it.


If you think you want to subclass function, consider whether you can
do what you want with decorator syntax.


Carl Banks
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to