Python 中的类与类型 [英] Class vs. Type in Python

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

问题描述

我最近才开始自学如何编码.我目前正在阅读 Think Python 2 for python 3,当它讲授 type() 函数时,它给出了示例 type(2)它输出 .然后它指出‘类’这个词是在一个类别的意义上使用的;一个类型是一个值的类别."

让我困惑的部分是 type() 函数输出的是类而不是类型.另外,我不确定类型和类之间的区别;是值"类型的字符串、浮点数和整数类,还是相同的东西?

我已经查过了,但找不到我的具体问题的答案或简单到我能理解的答案.

解决方案

曾几何时,Python 有类型.类型是在 C 中定义的内置对象;类是您在使用 class 语句时构建的内容.两者的命名不同,因为您不能将它们混合在一起;类不能扩展类型.

这种差异是人为的,是语言实现的限制.从 Python 2.2 开始,Python 的开发者已经慢慢走向统一这两个概念,在 Python 3 中几乎没有区别.内置类型现在也标记为类,您可以随意扩展它们.

您的书试图解释 Python 中不再存在的差异.即使在 Python 2 中,区别也只是在名称上,因为 type(2) 显示这里仍然使用type"这个词:

<预><代码>>>>类型(2)<输入'int'>

但是您可以像任何其他类一样对 int 进行子类化.

(Python 2 仍然有旧式的类,那些不是从 object 继承的;这些是统一之前旧系统的残余.)

I just recently started to teach myself how to code. I am currently reading Think Python 2 for python 3 and when it teaches about the type() function, it gives the example type(2) which outputs <class 'int'>. It then states that "the word 'class' is used in the sense of a category; a type is a category of values."

The part that confuses me is that the type() function outputs class instead of type. Also, I'm not sure about the difference between type and class; are string, float point, and integer classes of the type "value", or are they the same thing?

I have looked this up but cannot find an answer to my specific questions or simple enough for me to understand.

解决方案

Once upon a time, Python had both types and classes. Types were built-in objects defined in C; classes were what you built when using a class statement. The two were named differently because you couldn't mix these; classes could not extend types.

This difference was artificial, a limitation in the language implementation. Starting with Python 2.2, the developers of Python have slowly moved towards unifying the two concepts, with the difference all but gone in Python 3. Built-in types are now also labelled classes, and you can extend them at will.

Your book is trying to explain a difference that isn't present in Python anymore. Even in Python 2 the difference is only there in name, since type(2) shows the word 'type' is still used there:

>>> type(2)
<type 'int'>

but you can subclass int just like any other class.

(Python 2 does still have old-style classes, those that don't inherit from object; these are a remnant of the old system from before the unification.)

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

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