首页 > 编程语言 > 详细

python 反射

时间:2019-05-30 00:24:50      阅读:130      评论:0      收藏:0      [点我收藏+]

1、反射:使用字符串类型的名称,操作变量

2、方法:hasattr(),getattr(),setattr(),delattr()

3、作用范围

面向对象(对象、方法)

模块(内置模块、自定义模块、反射自己的模块)

4、hasattr()和getattr()最重要,也最常用,一般一起出现,称为夫妻档;setattr()和delattr()了解即可

class Student:
    """
    1.tom是实例化的对象,反射:对象的属性、方法
    2.Student是类,反射:类的静态属性和类方法
    3.反射方法:获取的值要加(),有参数时,要添加参数
    4.hasattr()用于判断和getattr()可以看成夫妻档,一般成对出现
    """
    country = china

    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def info(self, new_grade):
        if self.grade < new_grade:
            return "恭喜"
        else:
            return "遗憾"

    @classmethod
    def coun(cls, new_country):
        Student.country = new_country


tom = Student(tom, 70)
if hasattr(tom, name):        # 对象属性反射
    print(getattr(tom, name))     # 结果:tom    

if hasattr(tom, info):
    ret = getattr(tom, info)      # 对象方法的反射
    print(ret(80))          # 结果:恭喜       

if hasattr(Student, coun):
    ret = getattr(Student, coun)      # 静态属性/类属性的反射
    ret(USA)

if hasattr(Student, country):     # 类方法的反射
    print(getattr(Student, country))      # 结果:USA
import sys
"""
1.反射自己的模块,实质是.py文件命令、函数的反射
2.sys.modules[__name__],获取当前文件对象
3.python一切皆对象
"""
name = tom


def output():
    return "Hello World!"


# print(sys.modules[__name__])    # 获取当前文件,python一切皆对象
if hasattr(sys.modules[__name__], name): 
    print(getattr(sys.modules[__name__], name))   # 结果:tom
if hasattr(sys.modules[__name__], output):
    ret = getattr(sys.modules[__name__], output)      #
    print(ret())       # 结果:Hello World!
"""
1.setattr(),Sets the named attribute on the given object to the specified value
2.delattr(), Deletes the named attribute from the given object.
"""


class Test:
    def sb(self):
        return sb


t1 = Test()
setattr(t1, name, china_lead)   # 设置对象t1的属性name和值china_lead
if hasattr(t1, name):
    print(getattr(t1, name))      # 结果:china_lead
try:
    delattr(t1, name)     # 通过反射删除对象的属性
    getattr(t1, name)
except Exception as error:
    print(result: %s % error)     # result: ‘Test‘ object has no attribute ‘name‘

 

python 反射

原文:https://www.cnblogs.com/wt7018/p/10946720.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!