Python高阶---反射

======================================

反射:

hasattr: 输入一个字符串,判断对象有没有这个方法或属性

getattr: 获取对象属性或方法的引用。

如果是方法,则返回方法的引用;

如果是属性,则直接返回属性值;

如果该方法或属性不存在,则抛出异常。

setattr: 动态添加一个方法或属性

delattr: 动态删除一个方法或属性

======================================

def talk():
print('二哈汪汪汪...')

class Dog:
def init(self, name):
self.name = name

def eat(self):
    print('{}正在吃'.format(self.name))

def sleep(self):
    print('{}正在睡'.format(self.name))

dog = Dog('二哈')
choice = input('请输入要执行的方法名称:') #

print(hasattr(dog, choice))

if hasattr(dog, choice):
try:
func = getattr(dog, choice) # getattr返回方法的引用
func() # 调用方法
except TypeError as e:
print(getattr(dog, choice))
else:
print("输入的方法不存在,请检查!")

attr = input("请输入要添加的属性名:")
value = input("请输入要添加的属性值:")
if value.isdigit():
# 如果用户输入的属性值为数值型
setattr(dog, attr, int(value)) # 动态绑定属性
else:
# 如果用户输入的属性值不是数值型
setattr(dog, attr, value)

print(dir(dog))
if hasattr(dog, attr):
print(getattr(dog, attr)) # 打印出我们之前设置的属性值

choice = input('请输入要设置的方法名:')
setattr(dog, choice, talk) # 通过choice指向实际要绑定的函数
getattr(dog, choice)()
print(dir(dog))

delattr(dog, choice)
getattr(dog, choice)()

========================

eval(expression, globals=None, locals=None)

exec(obj, [, globals[, locals]])

x = 10

def func():
y = 20
a = eval('x+y') # x=10, y=20
print("a=", a)
b = eval('x+y', {"x": 1, "y": 2}) # 计算中使用的是x=1,y=2
print("x=", x, "y=", y)
print("b=", b) #

c = eval('x+y', {"x": 1, "y": 2}, {"x": 3, "y": 4})   # 计算中使用的是x=3,y=4
print("x", x, "y", y)
print("c=", c)

d = eval('x+y', {"x": 1, "y": 2}, {"x": 3, "z": 5})   # 计算中使用的是x=3,y=2
print("x", x, "y", y)
print("d=", d)        # d = 5

func()

======================================

x = 1
y = exec('x = 1+1') # exec不会返回值
print(x) # x = 2
print(y) # None
exec('a=[]\na.append(2)')
print(a) # [2]

a = '[1,2,3,4,5]'
print(type(a))
print(type(eval(a)))
print(type(a))

a = "mydict = {'name':'jack'}"
print(type(a))
exec(a)
print(mydict)
print(type(mydict))

======================================

posted @ 2024-05-06 14:51  星空28  阅读(3)  评论(0编辑  收藏  举报