python面向对象编程(2):特殊方法
2017-08-09 23:19
393 查看
repr()和str()方法:
对于一个对象,python中提供了以上两种字符串的表示,它们的作用和repr()、str()、string.format()大体一致。如果需要把一个类的实例变成str对象,就需要实现特殊方法str()
-字符串的format()函数也可以使用这些方法,当我们使用{!r}或者{!s}格式时,我们实际上分别调用了repr()或者str()方法。
class student(object): def __init__(self,name,grade,score): self.name=name self.grade=grade self.score=score class collegestudent(student): def _status(self): return str(self.name),int(self.grade),int(self.score) a=collegestudent('daxing','3','59') print a print str(a)
结果
<__main__.collegestudent object at 0x383470> '<__main__.collegestudent object at 0x383470>'
返回的是这个类的地址,并不能从中获得有效的东西
我们需要重写默认的repr()和str()
class student(object): def __init__(self,name,grade,score): self.name=name self.grade=grade self.score=score def __str__(self): return '(student: %s, %s, %s)' %(self.name,self.grade,self.score) class collegestudent(student): def _status(self): return str(self.name),int(self.grade),int(self.score) a=collegestudent('daxing','3','59') print a
结果为
(student: daxing, 3, 59)
format()方法
未完待续相关文章推荐
- Python面向对象编程(5)——类的特殊方法
- 洗礼灵魂,修炼python(33)--面向对象编程(3)—特殊类方法__init__,公有属性,私有属性
- python中面向对象编程的特殊方法
- Python_day8_面向对象(多态、成员修饰符、类中特殊方法、对象边缘知识)、异常处理之篇
- Python所有特殊方法, 魔术方法, 钩子
- python的特殊方法总结
- Python(私有变量)类中的特殊方法
- 【Python】面向对象--类的特殊成员方法
- 【转】 python特殊方法函数
- Python 对象特殊方法:(二)对象可调用接口
- Python深入01 特殊方法与多范式
- Python学习笔记(二)——特殊方法(续)
- Python中的__getitem__和__setitem__特殊方法
- Python——特殊属性与方法
- Python中的特殊方法
- Python进阶(五):特殊方法
- python面向对象编程(2)—— 实例属性,类属性,类方法,静态方法
- python anaconda 安装 环境变量 升级 以及特殊库安装的方法
- Python面试:类的特殊方法