Pythonのdictは奇妙な問題です
# -*- coding:utf-8 -*-
import os
from os import system
import socket
import traceback
import time
import datetime
import random
import json
def get_merge_server_ip():
return socket.gethostbyname(socket.gethostname())
def test_1():
MERGE_SERVER_IP_MAPPING_NUMBER={'127.0.0.1':1, '10.103.13.153':153, '10.103.13.155':155, '10.103.13.172':172}
a_key = '127.0.0.1'
print 'test_1==', type(a_key) #<type 'str'>
print 'test_1==', a_key # 127.0.0.1
print 'len_1==',len(a_key) # 9
print 'id_1==',id(a_key) # 140486280156720
return MERGE_SERVER_IP_MAPPING_NUMBER.has_key(a_key)
def test_2():
MERGE_SERVER_IP_MAPPING_NUMBER={'127.0.0.1':1, '10.103.13.153':153, '10.103.13.155':155, '10.103.13.172':172}
a_key = get_merge_server_ip()
print 'test_2==', type(a_key) #<type 'str'>
print 'test_2==', a_key # 127.0.1.1
print 'len_2==',len(a_key) # 9
print 'id_2==',id(a_key) # 140486279882480
return MERGE_SERVER_IP_MAPPING_NUMBER.has_key(a_key)
if __name__=='__main__':
value_1 = test_1()
value_2 = test_2()
print 'value_1==', value_1 # result is True
print 'value_2==', value_2 # result is False
MERGE_という名前の定義SERVER_IP_MAPPING_NUMBERのdictオブジェクトは、keyが‘127.0.0.1’である場合、dictはそのkeyを含むとみなす.keyがローカルのipアドレスを取得し、値も‘127.0.0.1’である場合、dictはそのkeyを含まないと判断し、dictオブジェクトはどのような根拠であるkeyを含むか否かを判断するのか.コードは次のとおりです.
出力結果:
/usr/bin/python2.7 /home/TestDIct.py
test_1== <type 'str'>
test_1== 127.0.0.1
len_1== 9
id_1== 140486280156720
test_2== <type 'str'>
test_2== 127.0.1.1
len_2== 9
id_2== 140486279882480
value_1== True
value_2== False
Process finished with exit code 0