Python之路,Day7 - 面向对象编程进阶

Python之路,Day7 - 面向对象编程进阶

一、isinstanse(obj,cls)和issubclass(sub,class)

  判断obj是否是类cls的对象

  判断sub是否是类class的子类

二、反射

  1.定义:程序可以访问、检查、修改它本身状态和行为的一种能力

  2.python中一切皆是对象, 以下方法适用类和对象

 1 class Person():
 2     def __init__(self,name,age):
 3         self.name = name
 4         self.age = age
 5 
 6 class Student(Person):
 7     def __init__(self,name,age):
 8         super(Student,self).__init__(name,age)
 9 
10     def study():
11         return 'studying'
12 
13     @staticmethod
14     def exam():
15         return 'examing'
16 
17 s =Student('sam',12)
18 
19 #查询类中是否有此属性
20 print(hasattr(s,'age'))
21 
22 #获取属性对应的参数
23 print(getattr(s,'age'))
24 
25 #新增属性
26 setattr(s,'sex','male')
27 print(s.__dict__)
28 #结果{'name': 'sam', 'age': 12, 'sex': 'male'}
29 print(hasattr(s,'sex'))  #True
30 print(getattr(s,'sex'))  #'male'
31 
32 #删除属性
33 delattr(s,'age')
34 print(s.__dict__)
35 #结果{'name': 'sam', 'sex': 'male'}
36 
37 #一切皆对象,类可以同样的操作
38 print(hasattr(s,'age'))   #True 
39 print(Student,'staticmethod')  #True
40 print(getattr(Student,'exam')())  #examing
41 
42 setattr(Student,'sex','male')
43 print(Student.__dict__)
44 #结果{.....'sex': 'male'}
45 
46 print(delattr(Student,'study'))
实例

    3.反射的好处:实现即插即用,事先把主要逻辑写好,只定义接口,后期再完善接口的功能

 1 class part():
 2     def start(self):
 3         print('代码已写完....')
 4 
 5 class all():
 6     def keepgo(self):
 7         if hasattr(part,'start'):
 8             print('keepgo')
 9         else:
10             exit('功能未实现')
即插即用

      4.动态导入模块

   

三、自定義屬性方法

__setattr__,__delattr__,__getattr__

四、__getattribute__

#当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,除非__getattribute__在执行过程中抛出异常AttributeError
 1 class Foo:
 2     def __init__(self,x):
 3         self.x=x
 4 
 5     def __getattribute__(self, item):
 6         print('不管是否存在,我都会执行')
 7 
 8 f1=Foo(10)
 9 f1.x
10 f1.xxxxxx
View Code

五、__setitem__,__getitem,__delitem__

 1 class Foo(object):
 2     def __getitem__(self, item):
 3         print('__getitem__',item)
 4 
 5     def __setitem__(self, key, value):
 6         print('__setitem__',key,value)
 7 
 8     def __delitem__(self, key):
 9         print('__delitem__',key)
10 
11 obj = Foo()
12 result =obj['k1']
13 obj['k2']='sam'
14 del obj['k1']
15 print(obj.__dict__)
16 
17 #执行结果
18 __getitem__ k1
19 __setitem__ k2 sam
20 __delitem__ k1
21 {}
View Code

六、__module__和__class__

       分别表示:当前操作在哪个模块、哪个类

七、__call__

  方法的执行是对象后面加(),或类后面加()()

断言:检查前面是否正确

 

posted @ 2018-05-29 23:05  Pynetwork  阅读(131)  评论(0编辑  收藏  举报