type() for new style classes - buggy?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Michal Vitecek

    type() for new style classes - buggy?

    hello,

    does the type() command work correctly for new style classes? i guess
    it does not, unfortunately. for example, for a new style class'
    instance it returns <class '__main__.Class Name'>, but for old style
    class' instance it returns <type 'instance'>.
    [color=blue][color=green][color=darkred]
    >>> import types
    >>> class A(object):[/color][/color][/color]
    pass[color=blue][color=green][color=darkred]
    >>> class B:[/color][/color][/color]
    pass[color=blue][color=green][color=darkred]
    >>> type(A())[/color][/color][/color]
    <class '__main__.A'>[color=blue][color=green][color=darkred]
    >>> type(B())[/color][/color][/color]
    <type 'instance'>[color=blue][color=green][color=darkred]
    >>> type(A()) == types.InstanceT ype[/color][/color][/color]
    0[color=blue][color=green][color=darkred]
    >>> type(B()) == types.InstanceT ype[/color][/color][/color]
    1

    how can one then determine what he's working with when he uses new
    style classes (either instance or class)?

    thank you,
    --
    fuf (fuf@mageo.cz)

  • Sidharth Kuruvila

    #2
    Re: type() for new style classes - buggy?



    In the case of new style classes type actually doubles up as a class
    constructor, so all classes including type itself are instances type.
    [color=blue][color=green][color=darkred]
    >>> class A(object):[/color][/color][/color]
    .... pass
    ....[color=blue][color=green][color=darkred]
    >>> a = A()
    >>> type(a)[/color][/color][/color]
    <class '__main__.A'>[color=blue][color=green][color=darkred]
    >>> type(A)[/color][/color][/color]
    <type 'type'>[color=blue][color=green][color=darkred]
    >>> isinstance(A, type)[/color][/color][/color]
    True[color=blue][color=green][color=darkred]
    >>> isinstance(a, type)[/color][/color][/color]
    False[color=blue][color=green][color=darkred]
    >>> isinstance(type , type)[/color][/color][/color]
    True[color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]

    hope this helps
    there is some documentation on new style classes you might want to read.
    The official home of the Python Programming Language

    particularly the first essay by Guido.




    Comment

    Working...