零基础入门学习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