码迷,mamicode.com
首页 > 其他好文 > 详细

Day 23 反射

时间:2018-04-18 21:24:09      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:imp   role   attr   get   ash   派生   div   对象   model   

 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)()

技术分享图片

 

技术分享图片

 

技术分享图片

技术分享图片


 

Day 23 反射

标签:imp   role   attr   get   ash   派生   div   对象   model   

原文地址:https://www.cnblogs.com/kateli/p/8877333.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!