加载中...

Reflect反射

Reflect反射

通过字符串操作类对象 或者 模块中的相关成员的操作

hasattr

# 检测对象/类是否有指定的成员
# return bool


class Father():
	pass

class Mother():
	pass
	
class Children(Father,Mother):
	eye = "蓝色的"
	weight = "1吨"
	
	def eat(self):
		print("小孩下生会喝奶")
	
	def drink(self):
		print("小孩下生喜欢喝勇闯天涯...")
		
	def __la(self):
		print("小孩自动啦,无法控制")
	
obj = Children()
	
# (1)hasattr() 检测]对象/类是否有指定的成员
# 对象

res = hasattr(obj,"eye")
print(res)   # return true 

# 类
res = hasattr(Children,"eat123")
print(res)   # return false

getattr

# getattr() 获取对象/类成员的值
# 属性或方法


class Father():
	pass

class Mother():
	pass
	
class Children(Father,Mother):
	eye = "蓝色的"
	weight = "1吨"
	
	def eat(self):
		print("小孩下生会喝奶")
	
	def drink(self):
		print("小孩下生喜欢喝勇闯天涯...")
		
	def __la(self):
		print("小孩自动啦,无法控制")

# 对象
res = getattr(obj,"weight")
print(res)
# 如果获取的值不存在,可以设置第三个参数,防止报错
res = getattr(obj,"weight123","抱歉这个值不存在")
print(res)


# 方法
# 通过类进行反射 (反射出来的是普通方法)
func = getattr(Children,"drink")
print(func)   #  <class 'function'>
func(1)


# 通过对象进行反射 (反射出来的是绑定方法)  自动传参了
func = getattr(obj,"drink")
print(func)   # <bound method Children.drink of <__main__.Children object at 0x000001394205B550>>
func()

setattr

# 设置对象/类成员的值
# 属性或方法
class Father():
    pass


class Mother():
    pass


class Children(Father, Mother):
    eye = "蓝色的"
    weight = "1吨"

    def eat(self):
        print("小孩下生会喝奶")

    def drink(self):
        print("小孩下生喜欢喝勇闯天涯...")

    def __la(self):
        print("小孩自动啦,无法控制")


obj = Children()
# 对象
setattr(obj, "skin", "黑人")
print(obj.skin)  # 黑人

# 类
setattr(Children, "skin", "土耳其人")
print(Children.skin)  # 土耳其人
print(obj.skin)   # 黑人

delattr

# 设置对象/类成员的值
# 属性或方法
class Father():
    pass


class Mother():
    pass


class Children(Father, Mother):
    eye = "蓝色的"
    weight = "1吨"

    def eat(self):
        print("小孩下生会喝奶")

    def drink(self):
        print("小孩下生喜欢喝勇闯天涯...")

    def __la(self):
        print("小孩自动啦,无法控制")


obj = Children()
# 对象
delattr(obj,"skin")
print(obj.skin)

# 类
delattr(Children,"skin")
print(Children.skin)

Reflect反射的使用

# 当前文件作为模块有一些方法
def func1():
    print("我是func1方法")


def func2():
    print("我是func2方法")


def func3():
    print("我是func3方法")


import sys

print(sys.modules)  # 系统字典  系统引用的模块  key 模块名  value obj
module = sys.modules["__main__"]
print(module,type(module))    # <module '__main__' from 'C:\\Users\\wbcde\\Desktop\\test\\main.py'> <class 'module'>
res = getattr(module, "func1")
print(res)   # 普通函数 <function func1 at 0x000001AF1203E310>






while True:
	strvar = input("请输入你想要使用的功能:")
	if hasattr(module,strvar):
		func = getattr(module,strvar)
		func()
	elif strvar.upper() == "Q":
		print("再见")
		break
	else:
		print("没有该成员~!")
posted @ 2024-03-19 19:58  江寒雨  阅读(25)  评论(0)    收藏  举报