PythonのSTR&のrepr
より多くのevalで使用されてREPR(< -クリックして)、より多くのSTRの文字列形式に変換するために使用されます
STR()&のrepr()
strが()とのrepr()は、文字列を返します
(ただし、STRを)のrepr()、結果は読むために人々のために、より適している返す読み取るために、より適切なインタプリタの結果を返します。
違い
例:
string = 'Hello World'
print(str(string), len(str(string)))
print(repr(string), len(repr(string)))
出力:
Hello World 11
'Hello World' 13
説明strが()文字列自体は残って返しますが、のrepr()は引用符で囲まれた文字列を返します。
__repr__&__str__
1つのクラスにおいて__repr__
、__str__
あなたは文字列を返すことができます
例:
クラス2つの方法が同時に存在します
class Test(object):
def __init__(self):
pass
def __repr__(self):
return 'from repr'
def __str__(self):
return 'from str'
test = Test()
print(test)
print(test.__repr__())
print(test.__str__())
出力:
from str
from repr
from str
ときにのみ、クラスメソッド__str__
class Test(object):
def __init__(self):
pass
def __str__(self):
return 'from str'
test = Test()
print(test)
print(test.__repr__())
print(test.__str__())
出力:
from str
<__main__.Test object at 0x105df89e8>
from str
ときにのみ、クラスメソッド__repr__
class Test(object):
def __init__(self):
pass
def __repr__(self):
return 'from repr'
test = Test()
print(test)
print(test.__repr__())
print(test.__str__())
出力:
from repr
from repr
from repr
説明print()
機能のは、ことを呼び出し、__str__
コマンドラインから直接起動が出力されたとき、__repr__
何のクラスが存在しない場合__str__
、時間が呼び出されます__repr__
が、ない場合は__repr__
、呼び出して行きません__str__