type 和 class 的区别是什么

2020-02-06 14:37:07 +08:00
 pythonee
python 和 lisp 好像都有这些概念,type 是什么意思呢
有个 Stackoverflow 有个回答是 "Types categorize objects, while classes tag objects."
引:
https://stackoverflow.com/questions/42540781/common-lisp-type-vs-class-distinctions/42543008#42543008
2290 次点击
所在节点    程序员
6 条回复
SoloCompany
2020-02-06 20:38:31 +08:00
abstract type and concrete class
bugcoder
2020-02-07 00:16:04 +08:00
shellus
2020-02-07 01:48:26 +08:00
你问的是编程语言的 class 和 type 的区别,还是自然语言中 type 和 class 的区别呢?
pythonee
2020-02-07 09:39:31 +08:00
@shellus 编程语言中的
CRVV
2020-02-07 13:20:11 +08:00
在别的语言里,比如 C++ 和 Java,有的类型是 class 有的不是。
在 Python 里面,所有的类型都是 class,这两个词没有本质的区别。

但是当你用 class 这个词的时候,代表了不同的 class 之间有继承关系,比如 built-in function 里的 issubclass 和 isinstance。
isinstance(True, int) 是 True

用 type 的时候通常指单独的类型本身,比如 built-in functions 里的 type。
type(True) == int 是 False
aijam
2020-02-07 14:46:26 +08:00
In Assembly or C, type determines the interpretation of a sequence of memory and the operations that can be performed on it. For example, if you interpret 4 bytes of data as int, you can perform arithmetic operations with it; but if you interpret the same 4 bytes as char[4], you will be able to iterate over it with some indices.
Such idea can be found in many other languages. Another example is when you do "type casting", you are basically indicating the compiler to treat the same sequence of bytes with a different interpretation, such that a different set of operations can be applied.
So, how can you create your own type, i.e. define your own interpretation and the set of operations on a piece of data? That's where classes come into the picture. In general, you can consider a class as a recipe of a user-defined type, in contrast to the built-in types which are already predefined for you.
Surely, types and classes are much more profound concepts, especially when putting in the context of different languages. If you want to dive deeper on this topic, I think you should learn a little more about types and "type class" in Haskell, and maybe try to find the connection between "type class" in Haskell and "abstract class"/"interface" in the OO world. Also, compare them with "struct" in C/C++ and see how those languages provide their own mechanisms for abstraction.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/642522

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX