零基础入门学习Python(19):对象(4)组合、绑定
2015-12-24 22:55
681 查看
零基础入门学习Python(19):对象(4)组合、绑定
这节先介绍一下组合:即直接把需要的类放进另一种类中去实例化[code]>>> class Teacher: def __init__(self,x): self.teacher = x >>> class Student: def __init__(self,y): self.student = y >>> class School: def __init__(self,x,y): self.teacherSchool = Teacher(x) #直接把需要的类放进去实例化 self.studentSchool = Student(y) def printSchool(self): print("The school has ",self.teacherSchool.teacher," teachers and ",self.studentSchool.student," students.") >>> school = School(10,100) >>> school.printSchool() The school has 10 teachers and 100 students.
再介绍一下类、类对象和实例对象
[code]>>> class A: #类 count = 0 >>> a = A() #类对象 >>> b = A() >>> a.count #类对象访问属性值即为类中属性的值 0 >>> b.count 0 >>> a.count += 10 #修改a对象属性值 >>> a.count 10 >>> b.count 0 >>> A.count 0 >>> A.count += 100 >>> b.count 100 >>> a.count #a实例覆盖了类A中的count值 10 >>> class B: def num(self): print("num") >>> a = B() >>> a.num() num >>> a.num = 1 #实例化后的a创建了一个x属性 >>> a.num 1 >>> a.num() #如果属性名跟方法名相同,属性会覆盖方法,此时相当于调用不存在的方法,所以会出错 Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> a.num() TypeError: 'int' object is not callable
最后再介绍一下绑定:Python严格要求方法需要有实例才能被调用,这种限制其实就是Python所谓的绑定概念。
[code]>>> class C: def setXY(self,x,y): self.x = x self.y = y def printXY(self): print("x = ", self.x,"y = ", self.y) >>> c = C() >>> c.setXY(2,7) >>> c.printXY() x = 2 y = 7 >>> c.__dict__ #查看对象所拥有的属性,返回字典类型 {'y': 7, 'x': 2} >>> C.__dict__ #属性值2和7仅属于对象c dict_proxy({'__module__': '__main__', 'printXY': <function printXY at 0x02699AE0>, 'setXY': <function setXY at 0x02148738>, '__dict__': <attribute '__dict__' of 'C' objects>, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None}) >>> del C #删除类之后,类的对象c的属性仍然存在 >>> c.x 2 >>> c.y 7
零基础入门学习Python(18):对象(3)继承
相关文章推荐
- 进击python第一篇:相遇
- python之模块py_compile用法(将py文件转换为pyc文件)
- Python爬虫 - 登录csdn
- 使用Pycharm安装Python第三方库
- Python第三方库安装技巧
- 【转】Python计算器小程序及文件IO
- python之模块pprint之常见用法
- 为Python安装pip工具
- python之模块poplib之常见用法
- 为Python安装easy_install工具
- python中__getitem__, __setitem__, __delitem__的使用
- python面向对象具体解释(上)
- Python爬虫学习系列教程
- Python爬虫入门八之Beautiful Soup的用法
- 有关 Python 2 和 Sublime Text 中文 Unicode 编码问题的分析与理解
- 【转】windows下python开发环境搭建
- python 生成 xml文件 属性的顺序问题
- python的urlparse
- 【转】 详细介绍windows下使用python pylot进行网站压力测试
- Python 标准库 urllib2 的使用细节