python面向对象编程(2):特殊方法
来源:互联网 发布:知乎成都工作 编辑:程序博客网 时间:2024/06/07 18:41
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=scoreclass collegestudent(student): def _status(self): return str(self.name),int(self.grade),int(self.score)a=collegestudent('daxing','3','59')print aprint 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()方法
未完待续
阅读全文
0 1
- python面向对象编程(2):特殊方法
- python中面向对象编程的特殊方法
- Python面向对象编程(5)——类的特殊方法
- Python面向对象5:特殊方法
- Python面向对象编程2
- python面向对象编程(2)
- python面向对象编程(2)—— 实例属性,类属性,类方法,静态方法
- JavaScript面向对象编程(2)对象上的特殊属性
- python面向对象编程
- python 面向对象编程
- python面向对象编程
- python面向对象编程
- Python 面向对象编程
- Python面向对象编程
- Python 面向对象编程
- python--面向对象编程
- python面向对象编程
- python 面向对象编程
- 643. Maximum Average Subarray I
- windows自带截屏快捷键
- 响应式编程101
- np.newaxis 的使用
- Stanford CoreNLP学习日记3
- python面向对象编程(2):特殊方法
- tyvj 1004 滑雪 dfs + dp
- Android Handler机制源码解析
- php匹配中文_英文_数字的正则表达式
- 在Action中获取表单提交数据
- JavaScript中dom对css样式操作
- 多线程面试
- 关于面向对象的一点小理解
- Android Material Design 之 NavigationView