微信搜索“菜鸟童靴”,选择“关注公众号”
我们一起开启Python进阶之旅!
内置函数repr介绍
repr_方法是Python类中的一个特殊方法,由于object类已经提供了该方法,而所有的Python类都是object类的子类,所以所有的Python对象,都具有_repr_方法
class test:
def __init__(self,name,age):
self.age = age
self.name = name
t = test("Zhou",30)
print(t)
以上代码的输出结果为:
print方法之所以能打印对应,正是由于每个类都有继承自object类的_repr_方法,在这里,print函数实际输出的是test对象_repr_方法的返回值,以下两行代码的结果是完全一致的:
print(t)
print(t._repr_())
_repr_方法默认返回该对象实现类的“类名+object at +内存地址”值
当然,我们也可以尝试自己重写该方法,来满足我们希打印出的信息
class test:
def __init__(self,name,age):
self.age = age
self.name = name
def __repr__(self):
return "Class_Test[name="+self.name+",age="+str(self.age)+"]"
t = test("Zhou",30)
print(t)
输入结果为:
Class_Test[name=Zhou,age=30]
通过重写_repr_方法,我们打印出了类名、以及其包含的属性名称、属性值
文章首发于微信公众号菜鸟童靴,不定期更新,如有需要后台加微信
参考文章:
https://blog.youkuaiyun.com/csdn_mr_h/article/details/90414524