V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
pythonee
V2EX  ›  程序员

type 和 class 的区别是什么

  •  
  •   pythonee · 2020-02-06 14:37:07 +08:00 · 2219 次点击
    这是一个创建于 1540 天前的主题,其中的信息可能已经有所发展或是发生改变。
    python 和 lisp 好像都有这些概念,type 是什么意思呢
    有个 Stackoverflow 有个回答是 "Types categorize objects, while classes tag objects."
    引:
    https://stackoverflow.com/questions/42540781/common-lisp-type-vs-class-distinctions/42543008#42543008
    6 条回复    2020-02-07 14:46:26 +08:00
    SoloCompany
        1
    SoloCompany  
       2020-02-06 20:38:31 +08:00
    abstract type and concrete class
    shellus
        3
    shellus  
       2020-02-07 01:48:26 +08:00
    你问的是编程语言的 class 和 type 的区别,还是自然语言中 type 和 class 的区别呢?
    pythonee
        4
    pythonee  
    OP
       2020-02-07 09:39:31 +08:00
    @shellus 编程语言中的
    CRVV
        5
    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
        6
    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.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5395 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 08:41 · PVG 16:41 · LAX 01:41 · JFK 04:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.