我是靠谱客的博主 有魅力水蜜桃,这篇文章主要介绍python学习笔记之(八),现在分享给大家,希望可以做个参考。

面向对象高级编程

我们定义一个class,可对其的实例绑定属性:

复制代码
1
2
3
4
5
6
7
>>> class Student(object): pass >>> s = Student() >>> s.name = 'M' >>> print s.name M

也可以绑定方法(注意绑定方法的格式):

复制代码
1
2
3
4
5
6
7
8
9
>>> def set_age(self, age): self.age = age >>> from types import MethodType >>> s.set_age = MethodType(set_age, s, Student) >>> s.set_age(25) >>> s.age 25

但是给一个实例绑定的方法对其他实例并不起作用:

复制代码
1
2
3
4
5
6
7
>>> s2 = Student() >>> s2.get_age(25) Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> s2.get_age(25) AttributeError: 'Student' object has no attribute 'get_age'

最后

以上就是有魅力水蜜桃最近收集整理的关于python学习笔记之(八)的全部内容,更多相关python学习笔记之(八)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(81)

评论列表共有 0 条评论

立即
投稿
返回
顶部