Python中的类型和类 [英] Types and classes in Python

查看:75
本文介绍了Python中的类型和类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python中的类型和类有点困惑。例如,以下REPL对话混淆了我:

 >>> A类:pass 
...
>>> a = A()
>>>> type(a)
< type'instance'>
>>>> a .__ class__
< class __main __。A at 0xb770756c>
>>>> type([])
< type'list'>
>>>> [] .__ class__
< type'list'>
>>>> type(list)
< type'type'>
>>>> list .__ class__
< type'type'>
>>>> type(A)
< type'classobj'>
>>>> A .__ class__
回溯(最近最后一次调用):
在< module>中的文件< stdin>
AttributeError:class A没有属性'__class__'




  1. 为什么内置的东西的类型和类(例如这里的列表)对于用户类/类型是相同的但不同的?

  2. 不是每个类都是一些其他类的实例Java)?为什么对于用户定义的类没有 __ class __

可以澄清这种行为会非常感激。 TIA。

解决方案

新式风格类与经典类遇到不同的行为。如需进一步阅读,请参阅: Python数据模型。具体阅读关于类的部分以及新式样和经典类之间的区别。



尝试在您的REPL中输入以下内容:

  class A:pass 
class B(object):pass

,你会看到你得到不同的结果。这里你处理新风格和旧风格类之间的区别。使用Python 2.6.1这里是我得到:

 > type(A)
< typeclassobj>
>类型(B)
< typetype>

它告诉你列表是新样式类而不是旧样式类。我们还可以使用列表进一步玩耍:

  ; type(list)
< typetype>


与我们的 B类(对象)相同:pass 结果。还

 > c = [] 
> type(c)
< typelist>

这告诉你对象的实例,而不是它的定义。


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()
>>> type(a)
<type 'instance'>
>>> a.__class__
<class __main__.A at 0xb770756c>
>>> type([])
<type 'list'>
>>> [].__class__
<type 'list'>
>>> type(list)
<type 'type'>
>>> list.__class__
<type 'type'>
>>> type(A)
<type 'classobj'>
>>> A.__class__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class A has no attribute '__class__'

  1. Why is the type and class for inbuilt things (e.g. list here) the same but different for user classes/types?
  2. Isn't every class an instance of some other class (like Class in Java)? Why no __class__ for user defined classes?

Any explanation/further reading which can clarify this behaviour would be much appreciated. TIA.

解决方案

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.

这篇关于Python中的类型和类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆