Python入门day33——反射、内置方法

反射

1.什么是反射?
主要是指程序可以访问、检测和修改它本身状态或行为的一种能力(自省)。
2.为何要用反射?
在程序运行过程中可以"动态"获取对象的信息。

3.如何实现反射?

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('yu',18)

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

# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name', 'say']

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

# 通过四个内置函数实现反射:通过字符串来操作属性值
# 1、hasattr()
print(hasattr(obj,'name')) # True
print(hasattr(obj,'x')) # False

# 2、getattr()
print(getattr(obj,'name')) # yu 相当于obj.name  

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

# 4、delattr()
delattr(obj,'name') # del obj.name
print(obj.__dict__) # {'age': 18}

res1=getattr(obj,'say') # obj.say
res2=getattr(People,'say') # People.say
print(res1) # <bound method People.say of <__main__.People object at 0x000001D1C4D93AF0>>
print(res2) # <function People.say at 0x000001D1C6949040>

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

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

内置方法

1、什么是内置方法?
定义在类内部,以__开头并以__结尾的方法
特点:会在某种情况下自动触发执行
2、为何要用内置方法?
为了定制化我们的类or对象
3、如何使用内置方法
#__str__:在打印对象时会自动触发,然后将返回值(必须是字符串类型)当做本次打印的结果输出
class People:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "<%s:%s>" %(self.name,self.age)

obj = People('yu', 18)

# print(obj.__str__()) # <'yu':18>
print(obj)  # <'yu':18>  # <__main__.People object at 0x00000285462D3AF0>

obj1=int(10)
print(obj1) # 10

# __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之前  执行结果就是相反run...在==========>之前
print('============>')

# 结果
============>
run...
原文地址:https://www.cnblogs.com/yding/p/12708646.html