python 类的repr函数

class Human:
    def __init__(self,name,age):
        self.name,self.age=name,age
    def __str__(self):
        return f'{self.age}岁的{self.name}'
    def __repr__(self):
        return 'Human('+repr(self.name)+','+repr(self.age)+')'




h1=Human("张三",18)
print(h1)
s1=repr(h1)
print(s1)
h2=eval(s1)
print(h2)
print("%r"%h1)#r用repr方法
print("%s"%h1)#s 用str方法

 

posted @ 2025-12-09 21:00  myrj  阅读(1)  评论(0)    收藏  举报