Python学习笔记(七)更加抽象
Python学习笔记(七)更加抽象
本章主要介绍内容为创建自己的对象:
7.2 创建自己的类
首先看使用一个简单的类
_metaclass_=type >>> class Person: def setName(self,name): self.name=name def getName(self): return self.name def greet(self): print ("hello %s " %self.name)
self参数相当于对对象自身的引用,可以参考C++中的this 指针
>>> daxiao=Person() >>> daxiao.setName("daxiao") >>> daxiao.getName() 'daxiao' >>> daxiao.greet() hello daxiao
7.2.3私有化
默认情况下,程序可以从外部访问一个对象的特性。就如上面的例子那样。
Python并不支持直接私有的方式,但是可以利用一些小技巧达到私有特性的效果
class Secretive: def __inaccessible(self): print("belt you can't see me") def accessible(self): self.__inaccessible() >>> a=Secretive() >>> a.__inaccessible() Traceback (most recent call last): File "", line 1, in a.__inaccessible() AttributeError: 'Secretive' object has no attribute '__inaccessible' >>> a.accessible() belt you can't see me
没错,就是在函数名前加双下划线。这样函数只能被类的内部调用。
其实,在类的内部调用中,所有加双下划线开始的名字都被翻译成前面加上单下划线和类名的形式。如果想访问“私有”函数,只需
a._Secretive__inaccessible() belt you can't see me
简而言之,确保其他人不会访问对象的方法和特性是不可能的。
7.2.5 指定超类
子类可以扩展超类的定义,将其他类名写在class语句后的圆括号内可以指定超类
class father: def a(self): print("i am man") def b(self): print("i am older") class son(father): def b(self): print("i am younger")
b=son() >>> a.a() i am man >>> a.b() i am older >>> b.a() i am man >>> b.b() i am younger
当然 也可以继承多个超类
class father: def a(self): print("i am man") def b(self): print("i am older") class mother: def c(self): print("i am human") class son(father,mother): def b(self): print("i am younger")
>>> b=son() >>> b.a() i am man >>> b.b() i am younger >>> b.c() i am human
注意,先继承的超类中的方法会重写后继承的超类中的方法
7.2.8 接口和内省
在面对多态对象时,可能需要判断其究竟具有哪些方法。比如上例中的b对象,包含a,b,c三个方法
>>> hasattr(b,'a') True >>> hasattr(b,'d') False
小结
对象
类
多态
封装
继承
接口和内省
评论关闭