零基础入门学习Python(19):对象(4)组合、绑定

零基础入门学习Python(19):对象(4)组合、绑定

这节先介绍一下组合:即直接把需要的类放进另一种类中去实例化

>>> 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.

再介绍一下类、类对象和实例对象

>>> 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所谓的绑定概念。

>>> 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)继承

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值