软件测试学习 之 Python 变量赋值疑问

赋予相同的值,比较id和hashcode,控制台和pycharm执行结果不一致

def compare(a_, b_):
    print("a=%r,b=%r" % (a_, b_))
    print("id(a)==id(b):%r" % (id(a_) == id(b_)))
    print("id(a)=%r,id(b)=%r" % (id(a_), id(b_)))
    print("a is b:%r" % (a_ is b_))
    print("a==b:%r" % (a_ == b_))
    print("hash(a)==hash(b):%r" % (hash(a_) == hash(b_)))
    print("hash(a)=%r,hash(b)=%r" % (hash(a_), hash(b_)))


a = 65535
b = 2 ** 16 - 1
compare(a, b)
print()

a = "hello"
b = "hello"
compare(a, b)
print()

a = "hello world"
b = "hello world"
# 在ipython中执行'a is b'结果=False
# 执行py源程序'a is b'结果=True
compare(a, b)
print()

a = "hello world"
b = "hello" + " " + "world"
# 在ipython中执行'a is b'结果=False
# 执行py源程序'a is b'结果=True
compare(a, b)

pycharm执行结果如下:

a=65535,b=65535
id(a)==id(b):True
id(a)=32019568,id(b)=32019568
a is b:True
a==b:True
hash(a)==hash(b):True
hash(a)=65535,hash(b)=65535

a='hello',b='hello'
id(a)==id(b):True
id(a)=32003328,id(b)=32003328
a is b:True
a==b:True
hash(a)==hash(b):True
hash(a)=3473501562964729520,hash(b)=3473501562964729520

a='hello world',b='hello world'
id(a)==id(b):True
id(a)=36892720,id(b)=36892720
a is b:True
a==b:True
hash(a)==hash(b):True
hash(a)=-6232109452232094900,hash(b)=-6232109452232094900

a='hello world',b='hello world'
id(a)==id(b):True
id(a)=36892720,id(b)=36892720
a is b:True
a==b:True
hash(a)==hash(b):True
hash(a)=-6232109452232094900,hash(b)=-6232109452232094900

在ipython中执行结果如下:

a=65535,b=65535
id(a)==id(b):False
id(a)=80099472,id(b)=79806672
a is b:False
a==b:True
hash(a)==hash(b):True
hash(a)=65535,hash(b)=65535

a='hello',b='hello'
id(a)==id(b):True
id(a)=87162696,id(b)=87162696
a is b:True
a==b:True
hash(a)==hash(b):True
hash(a)=1932490263531218073,hash(b)=1932490263531218073

a='hello world',b='hello world'
id(a)==id(b):False
id(a)=88423216,id(b)=88420912
a is b:False
a==b:True
hash(a)==hash(b):True
hash(a)=-175677020165839396,hash(b)=-175677020165839396

a='hello world',b='hello world'
id(a)==id(b):False
id(a)=88422256,id(b)=88423024
a is b:False
a==b:True
hash(a)==hash(b):True
hash(a)=-175677020165839396,hash(b)=-175677020165839396

参考解释:

Python常量池

       1.整数范围: -5 -- 257
       2.它永远不会被GC机制回收, 只要定义的整数变量在 范围: -5  --  256内,会被全局解释器重复使用, 257除外
       3.只要在这个 -5  --  256 范围内,创建同一区域代码块的变量的值如果是相等的,那么不会创建新对象(python万物皆对象,数值也是对象),直接引用。

def test_a():
    a = 123
    print(id(a))


def test_b():
    b = 123
    print(id(b))


c = 123
print(id(c))
test_a()
test_b()

测试结果如下:
1744793632
1744793632
1744793632

 特殊的257

def test_a():
    a = 257
    b = 257
    print(id(a))
    print(id(b))


num1 = 257
num2 = 257
print(id(num1))
print(id(num2))
test_a()

Pycharm执行结果如下:
1872078405424
1872078405424
1872077827792
1872077827792
这个整数对象是区分作用域的,它只有在相同的作用域, 内存地址才会相同

IPython执行结果如下:
79688848
83964144
83964208
83964208

相关问题
提问:python字符串是如何存储在内存中的 ?
提问者:v_ae
出处:csdn

字符串里如果出现了空格,带有空格符的字符串身份标识上是不同的?

猜你喜欢

转载自blog.csdn.net/jian3x/article/details/88924373