039类和对象:拾遗


1.组合:把类的实例话放到一个新类里面
       python的继承很有用,但容易把代码复杂化以及依赖隐含继承。因此,可以用组合代替。
       直接在类定义中把需要的类放进去实例化就可以了

   那什么时候用组合,什么时候用继承呢?
       组合:“有一个”,例如,水池里有一个乌龟,天上有一个鸟。
       继承:“是一个”,例如,青瓜是瓜,女人是人,鲨鱼是鱼。
 如:1 #!/usr/bin/python
  2 #coding:utf8
  3
  4 class Turtle:
  5     def __init__(self,x):
  6         self.num = x
  7
  8 class Fish:
  9     def __init__(self,x):
 10         self.num = x
 11
 12 class Pool:
 13     def __init__(self,x,y):
 14         self.turtle = Turtle(x)      #类的实例化
 15         self.fish = Fish(y)          #类的实例化
 16
 17     def print_num(self):
 18         print("水池里共有乌龟%d只,小鱼%d条" (self.turtle.num,self.fish.num))
 19
 20 pool = Pool(1,10)
 21 pool.print_num()

2.类、类对象和实例对象
  当类定义完的时候,类定义就变成了类对象,可以直接通过"类名.属性"或者"类名.方法名()"引用属性和方法
>>> class C:
...     count = 0
...
>>> a = C()
>>> b = C()
>>> c = C()
>>> a.count
0
>>> b.count
0
>>> c.count
0
>>> c.count += 10
>>> c.count
10
>>> a.count
0
>>> b.count
0
>>> C.count += 100
>>> a.count
100
>>> b.count
100
>>> c.count
10
>>> C.count
100

3.如果属性和名字和方法相同,属性会把方法覆盖掉
 如:>>> class C:
    ...     def x(self):   #定义x方法
    ...         print("X-man")
    ...
    >>> c = C()
    >>> c.x()              #调用C类的x方法
    X-man
    >>> c.x = 1            #此时给实例对象c定义一个x属性并赋值1
    >>> c.x                #调用c的x属性是正常的
    1
    >>> c.x()              #但此时再调用x方法就不可以了,因为重名的x属性覆盖了x方法
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'int' object is not callable


4.什么是绑定?
   python严格要求方法需要有实例才能被调用,这种限制就是绑定
 如:>>> class B:
    ...     def printB(self):
    ...         print("BB")
    ...
    >>> B.printB()     #没有实例化直接调用方法会报错
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unbound method printB() must be called with B instance as first argument (got nothing instead)
    >>> b = B()
    >>> b.printB()     #实例化以后再调用就没有问题了
    BB


练习:
1.在类中定义一个变量,用来追踪有多少个实例被创建
  实例化一个对象,变量+1;销毁一个对象,变量-1
  1 #!/usr/bin/python
  2 #coding:utf8
  3
  4 class AA:
  5     count = 0
  6     def __init__(self):
  7         AA.count += 1
  8
  9     def __del__(self):
 10         AA.count -= 1
 11 a = AA()
 12 b = AA()
 13 c = AA()
 14 print(AA.count)
 15 del a,b
 16 print(AA.count)
  运行结果为3,1

2.定义一个栈(Stack)类,用于模拟一种具有后进先出(LIFO)特性的数据结构
  方法:isEmpty():判断当前栈是否为空(返回True或Talse)
       push():往栈的顶部压入一个数据项
       pop():从栈顶弹出一个数据项(并在栈中删除)
       top():显示当前栈顶的一个数据项
       bottom():显示当前栈底的一个数据项
  1 #!/usr/bin/python                                         
  2 #coding:utf8
  3
  4 class Stack:
  5     def __init__(self,stack=[]):
  6         self.stack = []
  7         for x in stack:
  8             self.push(x)
  9
 10     def isEmpty(self):
 11         return not self.stack
 12
 13     def push(self,obj):
 14         self.stack.append(obj)
 15
 16     def pop(self):
 17         if not self.stack:
 18             print("Stack is empty!")
 19         else:
 20             return self.stack.pop()
 21
 22     def top(self):
 23         if not self.stack:
 24             print("Stack is empty!")
 25         else:
 26             return self.stack[-1]
 27
 28     def bottom(self):
 29         if not self.stack:
 30             print("Stack is empty!")
 31         else:
 32             return self.stack[0]
 33
 34 s = Stack()
 35 s.push(1)
 36 s.push(2)
 37 s.push(3)
 38 print"插入数字1,2,3:"
 39 print "top:",s.top()
 40 print "bottom:",s.bottom()
 41 print "pop1:",s.pop()
 42 print "pop2:",s.pop()
 43 print "pop3:",s.pop()
 44 print "isEmpty:",s.isEmpty()

运行结果:# python Stack.py
插入数字1,2,3:
top: 3
bottom: 1
pop1: 3
pop2: 2
pop3: 1
isEmpty: True

posted @ 2015-10-16 23:31  淡蓝色的天空很美  阅读(519)  评论(0编辑  收藏  举报