質問はそれを言います。
ここで少し説明します。
PHPで。「==」は次のように機能します
2=="2" (Notice different type)
// True
Python の場合:
2=="2"
// False
2==2
// True
php の python "==" に相当するのは "===" です
2===2
//True
2==="2"
//False
百万ドルの質問. PHPの「==」はPythonで何に相当しますか?
質問はそれを言います。
ここで少し説明します。
PHPで。「==」は次のように機能します
2=="2" (Notice different type)
// True
Python の場合:
2=="2"
// False
2==2
// True
php の python "==" に相当するのは "===" です
2===2
//True
2==="2"
//False
百万ドルの質問. PHPの「==」はPythonで何に相当しますか?
Python は、ほとんどの場合、PHP のように型を強制しません。
明示的に行う必要があります。
2 == int('2')
また
str(2) == '2'
Python は数値型を強制的に変換し (float と整数を比較できます)、Python 2 は Unicode とバイト文字列型の間で自動変換も行います (多くの人にとって残念なことです)。
1つもありません。等しいかどうかを確認する前に、型を変換する必要があります。あなたの例では、次のことができます
2==int("2")
これは似たようなものかもしれません:
x = 5
y = "5"
str(x) == str(y)
True
str(2) == str("2")
True
したがって、これはphpの==と同等です
def php_cmp(a, b):
if a is None and isinstance(b, basestring):
a = ""
elif b is None and isinstance(a, basestring):
b = ""
if a in (None, False, True) or b in (None, False, True):
return bool(a) - bool(b)
if isinstance(a, (basestring, int, long, float)) and isinstance(b, (basestring, int, long, float)):
try:
return cmp(float(a), float(b))
except ValueError:
return cmp(a,b)
if isinstance(a, (tuple,list)) and isinstance(b, (tuple,list)):
if len(a) != len(b):
return cmp(len(a),len(b))
return cmp(a,b)
if isinstance(a, dict) and isinstance(b, dict):
if len(a) != len(b):
return cmp(len(a),len(b))
for key in a:
if key not in b:
raise AssertionError('not compareable')
r = cmp(a[key], b[key])
if r: return r
return 0
if isinstance(a, (basestring, int, long, float)):
return 1
if isinstance(b, (basestring, int, long, float)):
return -1
return cmp(a,b)
def php_equal(a, b):
return php_cmp(a,b) == 0
テスト:
>>> php_equal(2, '2')
True
オブジェクト モデルと配列の実装が異なるため、これは 100% 正しいわけではありませんが、比較のために型を自動的に変換する際にどのような問題が発生する可能性があるかについては、ある程度理解できるはずです。