A question regarding string instance uniqueness in python

前端 未结 4 1749
一个人的身影
一个人的身影 2020-12-21 08:37

I was trying to figure out which integers python only instantiates once (-6 to 256 it seems), and in the process stumbled on some string behaviour I can\'t see the pattern i

4条回答
  •  生来不讨喜
    2020-12-21 09:06

    Python is allowed to inline string constants; A,B,C,D are actually the same literals (if Python sees a constant expression, it treats it as a constant).

    str is actually a class, so str(whatever) is calling this class' constructor, which should yield a fresh object. This explains E,F,G (note that each of these has separate identity).

    As for H, I am not sure, but I'd go for explanation that this expression is too complicated for Python to figure out it's actually a constant, so it computes a new string.

提交回复
热议问题