zoukankan      html  css  js  c++  java
  • 反射

    # 什么是反射?
    # 指的是在程序运行过程中可以"动态(不见棺材不掉泪)"获取对象的信息

    # 为何要用反射?

    # 如何实现反射?
    # class People:
    # def __init__(self,name,age):
    # self.name=name
    # self.age=age
    #
    # def say(self):
    # print('<%s:%s>' %(self.name,self.age))
    #
    # obj=People('辣白菜同学',18)

    # 实现反射机制的步骤
    # 1、先通过多dir:查看出某一个对象下可以.出哪些属性来
    # print(dir(obj))

    # 2、可以通过字符串反射到真正的属性上,得到属性值
    # print(obj.__dict__[dir(obj)[-2]])

    # 四个内置函数的使用:通过字符串来操作属性值
    # 1、hasattr()
    # print(hasattr(obj,'name'))
    # print(hasattr(obj,'x'))

    # 2、getattr()
    # print(getattr(obj,'name'))

    # 3、setattr()
    # setattr(obj,'name','EGON') # obj.name='EGON'
    # print(obj.name)

    # 4、delattr()
    # delattr(obj,'name') # del obj.name
    # print(obj.__dict__)


    # res1=getattr(obj,'say') # obj.say
    # res2=getattr(People,'say') # People.say
    # print(res1)
    # print(res2)

    # obj=10
    # if hasattr(obj,'x'):
    # print(getattr(10,'x'))
    # else:
    # pass

    # print(getattr(obj,'x',None))


    # if hasattr(obj,'x'):
    # setattr(obj,'x',111111111) # 10.x=11111
    # else:
    # pass

    # class Ftp:
    # def put(self):
    # print('正在执行上传功能')
    #
    # def get(self):
    # print('正在执行下载功能')
    #
    # def interactive(self):
    # method=input(">>>: ").strip() # method='put'
    #
    # if hasattr(self,method):
    # getattr(self,method)()
    # else:
    # print('输入的指令不存在')

    # obj=Ftp()
    # obj.interactive()
    # 1、什么是内置方法?
    # 定义在类内部,以__开头并以__结果的方法
    # 特点:会在某种情况下自动触发执行

    # 2、为何要用内置方法?
    # 为了定制化我们的类or对象

    # 3、如何使用内置方法
    # __str__:在打印对象时会自动触发,然后将返回值(必须是字符串类型)当做本次打印的结果输出
    # class People:
    # def __init__(self, name, age):
    # self.name = name
    # self.age = age
    #
    # def __str__(self):
    # # print('运行了...')
    # return "<%s:%s>" %(self.name,self.age)
    #
    # obj = People('辣白菜同学', 18)
    #
    # # print(obj.__str__())
    # print(obj) # <'辣白菜同学':18>
    #
    # # obj1=int(10)
    # # print(obj1)

    # __del__:在清理对象时触发,会先执行该方法
    # class People:
    # def __init__(self, name, age):
    # self.name = name
    # self.age = age
    # self.x = open('a.txt',mode='w')
    # # self.x = 占据的是操作系统资源
    #
    # def __del__(self):
    # # print('run...')
    # # 发起系统调用,告诉操作系统回收相关的系统资源
    # self.x.close()
    #
    # obj = People('辣白菜同学', 18)
    # # del obj # obj.__del__()
    # print('============>')
  • 相关阅读:
    Hadoop面试题总结(三)——MapReduce
    Hadoop面试题总结(二)——HDFS
    Hadoop面试题(一)
    html table有跨行跨列时,设置td宽度失效
    ubuntu14.04 安装五笔输入法(fcitx)
    NetCore生产环境禁用Swagger教程
    使用Jenkins与Docker持续集成与发布NetCore项目(实操篇)
    解决 Docker Unable to load the service index for source https://api.nuget.org/v3/index.json 问题
    .net webapi 接收图片保存到服务器,并居中剪裁压缩图片
    .net webapi 接收 xml 格式数据的三种情况
  • 原文地址:https://www.cnblogs.com/0B0S/p/12706738.html
Copyright © 2011-2022 走看看