How and when does Python determine the data type of a variable?

后端 未结 3 864
执念已碎
执念已碎 2021-02-20 12:39

I was trying to figure out exactly how Python 3 (using CPython as an interpreter) executes its program. I found out that the steps are:

  1. Compilation of Python so

3条回答
  •  孤城傲影
    2021-02-20 13:22

    Python is built around the philosophy of duck typing. No explicit type checking takes place, not even during runtime. For example,

    >>> x = 5
    >>> y = "5"
    >>> '__mul__' in dir(x)
    >>> True
    >>> '__mul__' in dir(y)
    >>> True
    >>> type(x)
    >>> 
    >>> type(y)
    >>> 
    >>> type(x*y)
    >>> 
    

    The CPython interpreter checks if x and y have the __mul__ method defined, and tries to "make it work" and return a result. Also, Python bytecode never gets translated to machine code. It gets executed inside the CPython interpreter. One major difference between the JVM and the CPython virtual machine is that the JVM can compile Java bytecode to machine code for performance gains whenever it wants to (JIT compilation), whereas the CPython VM only runs bytecode just as it is.

提交回复
热议问题