0%

反射

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# -*- coding:utf-8 -*-
# @Time :2022/6/25 12:06
# @SOFTWARE :python基础

# 反射
"""
通过字符串操作类对象或者模块中的相关成员的操作
hasattr() 检测对象/类是否有指定成员
getattr() 获取对象/类成员的值
setattr() 设置对象/类成员的值
delattr() 删除对象/类成员的值
"""

class Father():
pass

class Mother():
pass

class Child(Father,Mother):
eye = "黑色的"
weight = "10斤"

def eat(self):
print("吃奶奶")

def drink(self):
print("喝啤酒")

def __la(self):
print("拉粑粑")



obj = Child()

# (1) hasattr() 检测对象 / 类是否有指定成员
res = hasattr(obj,"eye")
print(res)
res = hasattr(Child,"eye")
print(res)

# (2) getattr() 获取对象/类成员的值
res = getattr(obj,"weight")
# 如果获取的值不存在,可以设置第三个参数,防止报错
res = getattr(obj,"1","2")
print(res)


# 通过类进行反射 反射出来的是普通方法
res = getattr(Child,"drink")
print(res)
res(2)

# 通过对象进行反射 反射出来的是绑定方法 bound method Child.drink of <__main__.Child object at 0x00000231E35E2FD0>>
res = getattr(obj,"drink")
print(res)
res()


# (3) setattr() 设置对象/类成员的值

setattr(obj,"skin","black")
print(obj.skin)

setattr(Child,"skin","wheet")
print(Child.skin)




# (4) delattr() 删除对象 / 类成员的值

delattr(obj,"skin")
print(obj.skin)
delattr(Child,"skin")
print(obj.skin)