python 重写__repr__与__str__函数
‘‘‘重写:将函数重写定义写一遍__str__():在调用print打印对象时自动调用,是给用户用的,是一个描述对象的方法。__repr__():是给机器用的,在Python解释器里面直接敲对象名在回车后调用的方法注意:在没有str时,且有repr,str = repr‘‘‘class Person(object): def __init__(self, name, age, height, weight): self.name = name self.age = age self.height = height self.weight = weight def __str__(self): return "%s-%d-%d-%d" % (self.name, self.age, self.height, self.weight)per = Person("hanmeimei", 20, 170, 55)#print(per.name, per.age, per.height, per.weight)print(per)#有点:当一个对象的属性值很多,并且都需要打印,重写了__str__方法后,简化了代码
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
世事一场大梦 2020-11-17
xiaoseyihe 2020-11-16
Morelia 2020-11-03
CloudXli 2020-11-03
文山羊 2020-10-31
comtop0 2020-10-31
pythonxuexi 2020-10-30
三石 2020-10-29
chaochao 2020-10-27
PythonMaker 2020-10-27