编程语言
首页 > 编程语言> > Python __repr__和__str__练习

Python __repr__和__str__练习

作者:互联网

'''
class Person(object):
instance = None

def __init__(self, name, age):
self.name = name
self.age = age

def __repr__(self): # 可读性高,给程序员输出结果
return f"reprname:{self.name},age;{self.age}"

def __str__(self): # 可读性高,给用户输出结果(优先级str>repr)
return f"str姓名:{self.name},年龄;{self.age}"

p1 = Person("huchangxi", 22)
p2 = Person("hulanxi", 6)
print(p1) # 姓名:huchangxi,年龄;22
print(p2) # 姓名:hulanxi,年龄;6
print(p1.name) # huchangxi

s = "hello"
print(repr(s)) #'hello'
print(s.__repr__())
'''

标签:__,name,Python,self,repr,str,age
来源: https://www.cnblogs.com/A121/p/16175905.html