程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The use of str() and repr() methods in Python

編輯:Python

One 、str() And repr() effect

Are used to convert objects into string output

Two 、 Example

class Foo:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return ("str full name :%s Age %s" % (self.name, self.age))
# def __repr__(self):
# return ("repr full name :%s Age %s" % (self.name, self.age))
if __name__ == '__main__':
f = Foo(' Zhang Fei ', '22')
print(f) # Equivalent to calling str(f), It is also equivalent to calling the class __str()__ Method

Output results :

str full name : Zhang Fei Age 22
class Foo:
def __init__(self, name, age):
self.name = name
self.age = age
# def __str__(self):
# return ("str full name :%s Age %s" % (self.name, self.age))
def __repr__(self):
return ("repr full name :%s Age %s" % (self.name, self.age))
if __name__ == '__main__':
f = Foo(' Zhang Fei ', '22')
print(f) # Equivalent to calling str(f), It is also equivalent to calling the class __str()__ Method

Output results :

repr full name : Zhang Fei Age 22

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved