1.預設情況下在直譯器中檢視cat物件和列印物件
>>
>
class
cat(
object):
...def
__init__
(self, color):.
.. self.color = color..
.>>
> my_cat = cat(
'yellow'
)>>
> my_cat
<__main__.cat object at 0x000001c35dd2e320
>
>>
>
print
(my_cat)
<__main__.cat object at 0x000001c35dd2e320
>
2.新增兩個轉換字串的方法時>>
>
class
cat(
object):
...def
__init__
(self,color):.
.. self.color = color..
.def
__repr__
(self):.
..return
'__repr__ cat'..
.def
__str__
(self):.
..return
'__str__ cat'
使用__repr__
的情況:
使用__str__
的情況:
示例**如下:
>>
> red_cat
__repr__ cat
>>
>
str(
[red_cat]
)'[__repr__ cat]'
>>
>
repr
(red_cat)
'__repr__ cat'
>>
>
print
(red_cat)
__str__ cat
>>
>
str(red_cat)
'__str__ cat'
3.兩種方法的小結
__repr__
的結果應該是無歧義的,__str__
的結果應該是可讀的。
總是為類新增__repr__
。__str__
預設情況下會呼叫__repr__
。
str與repr 改變物件的字串顯示
1 class foo 2 num 334 def init self,name,age 5 self.name name 6 self.age age78 def str self 自己定製列印資訊 9return 新的自定製顯示的方法名字是 s 年齡是 s self.name,self.age ...
str與repr的區別
python列印值的時候會保持該值在python 中的狀態,不是使用者所希望看到的狀態。而使用print列印值則不一樣,print列印出來的值是使用者所希望看到的狀態。例如 hello,world hello,world python列印出來的值是給python理解的,這裡python理解為字串,所...
字串操作 str
len str 獲取字串長度 str.find 查詢,從頭到尾找到第乙個符合的就停止 str.rfind 查詢,從尾到頭找到第乙個符合的就停止 沒有找到字串的時候返回 1 str.index 類似find str.rindex 類似rfind 沒有找到字串的時候報錯 str.startswith 以...