Types and classes in Python

后端 未结 3 565
离开以前
离开以前 2021-02-05 08:36

I\'m a bit confused about types and classes in Python. For e.g. the following REPL conversation confuses me:

>>> class A: pass
... 
>>> a = A()         


        
相关标签:
3条回答
  • 2021-02-05 08:56

    You're encountering the different behavior for new style classes versus classic classes. For further reading read this: Python Data Model. Specifically read the section on classes and the difference between new style and classic classes.

    Try typing the following into your REPL:

    class A: pass
    class B(object): pass
    

    and you'll see that you get different results. Here you're dealing with the difference between new style and old style classes. Using Python 2.6.1 here's what I get:

    > type(A)
    <type "classobj">
    > type(B)
    <type "type">
    

    which tells you that lists are new style classes and not old style classes. We can further play around with things using list as well:

    > type(list)
    <type "type">
    

    same as our class B(object): pass result. And also

    > c = []
    > type(c)
    <type "list">
    

    which is telling you about the instance of the object and not it's definition.

    0 讨论(0)
  • 2021-02-05 09:02

    It's "Hystorical reasons". Or possible "Histerical". It's all fixed in Python 3:

    >>> class A: pass
    ... 
    >>> a = A()
    >>> type(a)
    <class '__main__.A'>
    >>> a.__class__
    <class '__main__.A'>
    >>> type([])
    <class 'list'>
    >>> [].__class__
    <class 'list'>
    >>> type(list)
    <class 'type'>
    >>> list.__class__
    <class 'type'>
    >>> type(A)
    <class 'type'>
    >>> A.__class__
    <class 'type'>
    >>> class B(object): pass
    ... 
    >>> type(B)
    <class 'type'>
    >>> b = B()
    >>> type(b)
    <class '__main__.B'>
    
    0 讨论(0)
  • 2021-02-05 09:17

    In Python 3.0, user-defined class objects are instances of the object named type, which is itself a class. • In Python 2.6, new-style classes inherit from object, which is a subclass of type; • classic classes are instances of type and are not created from a class.

    0 讨论(0)
提交回复
热议问题