Day 23 反射

 isinstance
isinstance(obj,cls)检查是否obj是类cls的对象
class Foo(object):
    pass
obj = Foo()
print(isinstance(obj,Foo))

issubclass
issubclass(sub,super)检查sub类是否是super的派生类
class Foo(object):
    pass

class Bar(Foo):
    pass

print(issubclass(Bar,Foo))

 python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)
class Foo:
    role = 'person'
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def func(self):
        print('hi,%s'%self.name)

p = Foo('alex',26)
检查是否含有某属性 return whether the object has an attribute with the given name
# print(hasattr(p,'name'))
# 获取属性 getattr(object,name,default = None)
print(getattr(p,'age')) #属性
print(getattr(p,'func')) #方法
func = getattr(p,'func')
func()
# 设置属性 setattr(x,y,z) sets the named attribute on the given object to the specified value
setattr(p,'name','nero')
print(p.__dict__)
setattr(p,'show_name',lambda self:self.name +'sb')
print(p.show_name(p))
# 删除属性 delattr(x,y)   Deletes the named attribute from the given object.
delattr(p,'age')
delattr(p,'show_name')
delattr(p,'show_name111') #报错

print(p.__dict__)
# 类也是对象
class Foo(object):
    staticField = 'old boy'

    def __init__(self):
        self.name = 'wupeiqi'

    def func(self):
        return 'func'

    @staticmethod
    def bar():
        return 'bar'

print(getattr(Foo,'staticField'))
print(getattr(Foo,'func'))
print(getattr(Foo,'bar'))
# 反射当成模块成员
import sys

def s1():
    print (s1)

def s2():
    print(s2)

this_module = sys.modules[__name__]

print(hasattr(this_module,'s1'))
print(getattr(this_module, 's2'))
# 导入其他模块,利用反射查找该模块是否存在某个方法
'''
程序目录:
module_test.py
index.py

当前文件:
index.py
'''

import model_test as obj

print(hasattr(obj,'test'))
getattr(obj,'test')
# __len__
class A:
    def __init(self):
        self.a =1
        self.b =2

    def __len__(self):
        return len(self.__dict__)

a= A()
print(len(a))

#__hash__
class A:
    def __init__(self):
        self.a = 1
        self.b = 2
    def __hash__(self):
        return hash(str(self.a)+str(self.b))

a = A()
print(hash(a))
class A:
    role = 'person'
    def func(self):
        print('*'*self)
# ret = input('>>>')
# print(A.__dict__[ret])
print(getattr(A,'role'))    # 从A的命名空间里找一个属性 ,直接就可以找到这个属性的值
f = getattr(A,'func');f(2) # 从A的命名空间里找一个方法 ,找到的是这个方法的内存地址
getattr(A,'func')(2)
A.func(2)
# 类使用类命名空间中的名字
# 对象使用对象能用的方法和属性
# 模块使用模块中的名字
默写1
class A:
    role = 'Person'
    def __init__(self):
        self.money = 500
    def func(self):
        print('*'*10)

a = A()
print(a.func)
getattr(a,'func')()
print(getattr(a,'money'))
默写2
def
login(): print('执行login功能') def register(): print('执行register功能') import sys # 和python解释器相关的内容都在sys里 print(sys.modules['__main__']) func = input('>>>') if hasattr(sys.modules['__main__'],func): getattr(sys.modules['__main__'],func)()

 

 


 
posted on 2018-04-18 20:22  欣蔚  阅读(145)  评论(0编辑  收藏  举报