day 23 反射,内置函数,内置方法

补充两个内置函数

isinstance(a,B)  判断一个对象和一个类有没有血缘关系,能够检测到继承关系 

type(a) is A  type只是单纯判断对象和类,不能检测到继承

issubclass(子类名,父类名)如果返回True,说明有继承关系

 1 class B:pass
 2 class A(B):pass
 3 a = A()
 4 print(isinstance(a,A))
 5 print(isinstance(a,B))  # 能够检测到继承关系
 6 print(type(a) is A)
 7 print(type(a) is B)     # type只单纯的判断类
 8 
 9 
10 class B:pass
11 class C(B):pass
12 class D(C):pass
13 print(issubclass(C,D))
14 print(issubclass(D,C))
15 print(issubclass(B,C))
16 print(issubclass(C,B))
17 print(issubclass(D,B))

反射

1、什么是反射

反射的概念是由Smith在1982年首次提出的,主要是指程序可以访问、检测和修改它本身状态或行为的一种能力(自省)。这一概念的提出很快引发了计算机科学领域关于应用反射性的研究。它首先被程序语言的设计领域所采用,并在Lisp和面向对象方面取得了成绩。

2、python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)

四个可以实现自省的函数

下列方法适用于类和对象(一切皆对象,类本身也是一个对象)

1 def hasattr(*args, **kwargs): # real signature unknown
2     """
3     Return whether the object has an attribute with the given name.
4     
5     This is done by calling getattr(obj, name) and catching AttributeError.
6     """
7     pass
hasattr
1 def getattr(object, name, default=None): # known special case of getattr
2     """
3     getattr(object, name[, default]) -> value
4     
5     Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
6     When a default argument is given, it is returned when the attribute doesn't
7     exist; without it, an exception is raised in that case.
8     """
9     pass
getattr
1 def setattr(x, y, v): # real signature unknown; restored from __doc__
2     """
3     Sets the named attribute on the given object to the specified value.
4     
5     setattr(x, 'y', v) is equivalent to ``x.y = v''
6     """
7     pass
setattr
1 def delattr(x, y): # real signature unknown; restored from __doc__
2     """
3     Deletes the named attribute from the given object.
4     
5     delattr(x, 'y') is equivalent to ``del x.y''
6     """
7     pass
delattr
 1 class Foo:
 2     f = '类的静态变量'
 3     def __init__(self,name,age):
 4         self.name=name
 5         self.age=age
 6 
 7     def say_hi(self):
 8         print('hi,%s'%self.name)
 9 
10 obj=Foo('egon',73)
11 
12 #检测是否含有某属性
13 print(hasattr(obj,'name'))
14 print(hasattr(obj,'say_hi'))
15 
16 #获取属性
17 n=getattr(obj,'name')
18 print(n)
19 func=getattr(obj,'say_hi')
20 func()
21 
22 print(getattr(obj,'aaaaaaaa','不存在啊')) #报错
23 
24 #设置属性
25 setattr(obj,'sb',True)
26 setattr(obj,'show_name',lambda self:self.name+'sb')
27 print(obj.__dict__)
28 print(obj.show_name(obj))
29 
30 #删除属性
31 delattr(obj,'age')
32 delattr(obj,'show_name')
33 delattr(obj,'show_name111')#不存在,则报错
34 
35 print(obj.__dict__)
四个方法的使用演示
 1 class Foo(object):
 2  
 3     staticField = "old boy"
 4  
 5     def __init__(self):
 6         self.name = 'wupeiqi'
 7  
 8     def func(self):
 9         return 'func'
10  
11     @staticmethod
12     def bar():
13         return 'bar'
14  
15 print getattr(Foo, 'staticField')
16 print getattr(Foo, 'func')
17 print getattr(Foo, 'bar')
类也是对象
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 import sys
 5 
 6 
 7 def s1():
 8     print 's1'
 9 
10 
11 def s2():
12     print 's2'
13 
14 
15 this_module = sys.modules[__name__]
16 
17 hasattr(this_module, 's1')
18 getattr(this_module, 's2')
反射当前模块成员

导入其他模块,利用反射查找该模块是否存在某个方法

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 
4 def test():
5     print('from the test')
View Code
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3  
 4 """
 5 程序目录:
 6     module_test.py
 7     index.py
 8  
 9 当前文件:
10     index.py
11 """
12 
13 import module_test as obj
14 
15 #obj.test()
16 
17 print(hasattr(obj,'test'))
18 
19 getattr(obj,'test')()
View Code

__len__

1 class A:
2     def __init__(self):
3         self.a = 1
4         self.b = 2
5 
6     def __len__(self):
7         return len(self.__dict__)
8 a = A()
9 print(len(a))
View Code

__hash__

1 class A:
2     def __init__(self):
3         self.a = 1
4         self.b = 2
5 
6     def __hash__(self):
7         return hash(str(self.a)+str(self.b))
8 a = A()
9 print(hash(a))
View Code

 

posted @ 2018-05-03 21:09  大白1#  阅读(40)  评论(0)    收藏  举报