Python是一门面向对象编程的语言,自定义对象是Python语言的一个核心。
(1)多态
对不同类型的对象执行相同的操作许多函数和运算符都是多态的,自定义的函数大多也如此。一般来说,希望对象按期望执行,而非一定要求它是正确的类型,即“鸭子类型”:如果走起来像鸭子,叫起来像鸭子,那么它就是鸭子 #运算符多态(对数值和字符串都可以实现) >>> 1+2 3 >>> 'a'+'b' 'ab' #函数多态(对列表和字符串都可以实现) >>> def length(object): print('The length of ',repr(object),'is',len(object)) >>> length([1,2,3,4,5,6]) The length of [1, 2, 3, 4, 5, 6] is 6 >>> length('abcdefgh') The length of 'abcdefgh' is 8
(2)封装
对外部隐藏有关对象的工作原理的细节 #封装方法:with 方法的原理基本上不会过于关注,但都会使用 with open('a.txt','w') as f: for lines in f : print(lines) #自定义函数封装,调用他人函数时可以不必知道执行的细节 def run(speed,time=0): return '奔跑的距离是%dm'%(time *speed) >>> run(5,5) '奔跑的距离是25'
(3)继承
如果有了一个类,可以通过继承父类来调用父类的方法
(1)隐藏属性
可以将属性定义为私有,使其不能从对象外部访问,只能通过存取器方法(get_name,set_name)访问。私有形式:名称以两个下划线开头即可 class Secret: def __issecret(self): print("it's a secret") def not_secret(self): print("it's not a secret") >>> s.not_secret() it's not a secret >>> s.__issecret() Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> s.__issecret() AttributeError: 'Secret' object has no attribute '__issecret'
(2)继承深入
1) 指定超类(可以同时指定多个超类) 注:指定多个超类时(多重继承)如果多个超类以不同方式实现了同一个方法,必须小心排列这些超类,位于前面的类的方法将覆盖后面的类的方法。
class super_type: def init(self): pass def isstr(self,str1): pass class ssuper_type: def a_function(self): pass def b_function(self,str1): pass class sub_type(super_type,ssuper_type): #继承指定父类 def init(self): #重写init方法 pass2) 判断继承
BIF/方法描述issubclass(subclass,superclass)一个类是否是另一个类的子类isinstance(object,class)对象是否是特定类的实例class1.__bases__确定一个类的基类object1.__class__确定对象属于哪个类