《Python基础教程》学习笔记之二:更加抽象

本章没有非常详细的讲解类和对象。

7.1 对象的魔力

 

多态 Polymorphism

Polymorphism,令对不同的variable执行操作时,所用的method名以及用法都保持相同。这是统一的思想。换句话说,一个method可以适配多个不同类的variable。

 

封装 Encapsulation

对外部隐藏不必要的细节,让类和对象保持整洁,也保证了他们的安全。

 

继承 Inheritance

概念直白,没什么好说的。

 

7.2 类和类型

 

与类相关的名字

superclass, class, subclass

instance, method, attribute

 

用 isinstance() 判断对象是否为某一类型:

1 if isinstance(object, tuple):
2    return object[1]

其他判断函数如:type, issubclass 等。

 

类的创建

如果 method 需要使用类中的元素,比如 attribute,那么method的第一个参数须为self,即一个指向类本身的引用。

method也可以绑定到类外的一个普通function上,或者反之。

 

如何建立可靠的封装?可以参考以下思想:object中的attribute只能通过method访问和修改,专门因此创建的method称为accessor。

 

Python不直接支持私有方式,但如果想让method和attribute变为私有,可以在它的名字前面加上双下划线。

Secretive.__inaccessable 其实被翻译成 Secretive._Secretive__inaccessable (在__之前加上._classname)

也就是说,就算是加上了下划线,只要在类外需要访问该“私有成员”时,只要写成后者的形式即可。

 

类的命名空间 class namespace

位于class语句中的代码都在该命名空间下执行。这个命名空间可由类内所有成员访问。

1 class MemberCounter:
2     members = 0
3     def inint(self):
4         MemberCounter.members += 1

这样,每次初始化一个对象之后,members的值都会自增,在各个对象中访问这个members,得到的是一致的结果。不过,如果某个对象修改了这个变量,比如 object01.members = 'Mod',那么它的members值不再和其他对象保持一致,即屏蔽了类范围内的变量。

 

指定超类,重写method

1 class Filter:
2     def init(self):
3         self.blocked = []
4     def filter(self, sequence):
5         return [x for x in sequence if x not in self.blocked]
6 
7 class SPAMFilter(Filter):
8     def init(self):
9         self.blocked = ['SPAM']

 

接口和内省 Interfaces and Introspection

检查接口,就是检查一个对象是否有所需要的method和attribute。可以用hasattr检查,例如:hasattr(tc, 'talk')

posted @ 2012-06-13 22:25  atuskong  阅读(182)  评论(0)    收藏  举报