python反射机制

简介

1 魔术方法

反射就是通过字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员。

魔法方法简介
getattr根据字符串去某个模块中寻找方法
hasattr根据字符串去判断某个模块中该方法是否存在
setattr根据字符串去某个模块中设置方法
delattr根据字符串去某个模块中删除方法

2 使用示例

  • getattr
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Zero
import sys
import inspect


def function_test():
    print("function_test")

class Person(object):
    def __init__(self,name ):
        self.name = name

    def set_age(self,age):
        self.age = age

    def __str__(self):
        return "Class Person name:%s id:%s"%(self.name, id(self))

if __name__ == '__main__':
    person1 = Person("xiaowang")
    print(getattr(person1,'name'))   #从类中获得属性
    fun = getattr(person1,'set_age') #从类中获得方法
    if fun:
        fun(18)
    print(person1.age)
    print(person1)
    
'''
xiaowang
18
Class Person name:xiaowang id:1862869258192
'''
  • hasattr
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Zero
import sys
import inspect


def function_test():
    print("function_test")

class Person(object):
    def __init__(self,name ):
        self.name = name

    def set_age(self,age):
        self.age = age

    def __str__(self):
        return "Class Person name:%s id:%s"%(self.name, id(self))

if __name__ == '__main__':
    person1 = Person("xiaowang")
    print(hasattr(person1,'set_age'))
    print(hasattr(person1, 'name'))
    print(hasattr(person1, 'age'))
    person1.set_age(18)
    print(hasattr(person1, 'age'))
'''
True
True
False
True
'''
  • setattr和 delattr
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Zero
import sys
import inspect

def function_test():
    print("function_test")

class Person(object):
    def __init__(self,name ):
        self.name = name

    def set_age(self,age):
        self.age = age

    def __str__(self):
        return "Class Person name:%s id:%s"%(self.name, id(self))

if __name__ == '__main__':
    person1 = Person("xiaowang")
    setattr(person1,'name',"小明")
    setattr(person1,'age', 19)
    setattr(person1, 'sex', "man")
    print(person1)
    print(person1.age, person1.sex)
    print(hasattr(person1, 'sex'))
    delattr(person1, 'sex')
    print(hasattr(person1,'sex'))
'''
Class Person name:小明 id:1683276389728
19 man
True
False
'''

注:getattr,hasattr,setattr,delattr对模块的修改都在内存中进行,并不会影响文件中真实内容。

3 应用场景

  • 1 动态加载模块,固定目录加载插件一样写工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值