人若有情死得早 发表于 2017-7-15 22:52:32

039类和对象:拾遗

1.组合:把类的实例化放到新类里面,那么就能把新类组合进去了
class Turtle:
    def __init__(self, x):
      self.num = x

class Fish:
    def __init__(self, x):
      self.num = x

class Pool:
    def __init__(self, x, y):
      self.turtle = Turtle(x)
      self.fish = Fish(y)

    def print_num(self):
      print("水池里总共有乌龟 %d 只,小鱼 %d 条!" % (self.turtle.num, self.fish.num))

>>> pool = Pool(1, 10)
>>> pool.print_num()
水池里总共有乌龟 1 只,小鱼 10 条!
2.类、类对象和实例对象
类定义               C
类对象               C
实例对象   a         b         c
>>> 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
0
>>> C.count += 100
>>> a.count
100
>>> b.count
100
>>> c.count
10

>>> class C:
        def x(self):
                print("X-man!")

               
>>> c = C()
>>> c.x()
X-man!
>>> c.x=1
>>> c.x
1
>>> c.x()
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
    c.x()
TypeError: 'int' object is not callable
注意:
1)不要试图在一个类里边定义出所有能想到的特性和方法,应该利用继承和组合机制来进行扩展。
2)用不同的词性命名,如属性名用名词,方法名用动词。

3.绑定:Python严格要求方法需要有实例才能被调用,这种限制其实就是Python所谓的绑定概念。
>>> class BB:
        def printBB():
                print("no zuo no die")

               
>>> BB.printBB()
no zuo no die
>>> bb = BB()
>>> bb.printBB()
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
    bb.printBB()
TypeError: printBB() takes 0 positional arguments but 1 was given
>>> class CC:
        def setXY(self, x, y):
                self.x = x
                self.y = y
        def printXY(self):
                print(self.x, self.y)

               
>>> dd = CC()
>>> dd.__dict__
{}
>>> CC.__dict__
mappingproxy({'__dict__': <attribute '__dict__' of 'CC' objects>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, 'printXY': <function CC.printXY at 0x024D8270>, '__module__': '__main__', 'setXY': <function CC.setXY at 0x024D8228>, '__doc__': None})
>>> dd.setXY(4, 5)
>>> dd.__dict__
{'x': 4, 'y': 5}
>>> CC.__dict__
mappingproxy({'__dict__': <attribute '__dict__' of 'CC' objects>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, 'printXY': <function CC.printXY at 0x024D8270>, '__module__': '__main__', 'setXY': <function CC.setXY at 0x024D8228>, '__doc__': None})
>>> del CC
>>> ee = CC()
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
    ee = CC()
NameError: name 'CC' is not defined
>>> dd.printXY()
4 5
页: [1]
查看完整版本: 039类和对象:拾遗