反射

 

  1. 反射有四个方法:hasattr、getattr、setattr、delattr
  2. 最最重要的一点:通过字符串去操作对象的属性和方法,是字符串形式
  3. 什么对象可以用反射?
      • 实例化对象、类、其他模块、本模块
      • 只有以上四个才能使用,因为他们都能通过 . 的方式获取或调用,这也算是一种前
class A:

name = "海绵宝宝"

def func(self):
print(666)

content = input("请输入:").strip()
ret = getattr(A, content)
print(ret)
# 运行结果一:
请输入:name
海绵宝宝

# 运行结果二:
请输入:func
<function A.func at 0x7f4bdc6710d0>

# 运行结果三:
请输入:123
Traceback (most recent call last):
File "test01.py", line 9, in <module>
ret = getattr(A, content)
AttributeError: type object 'A' has no attribute '123'

# 原因解析:报错提示类 A 里面没有这个属性
# 也就是说,只有用户输入的是字符串形式的属于类 A 的属性时才不会报错




类名的反射操作

class A:

    country = "中国"
    area = "深圳"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def func(self):
        print(666)

# 获取类 A 的静态属性 country
print(getattr(A, "country"))    # 中国
# 获取类 A 的静态属性 area
print(getattr(A, "area"))       # 深圳
其他详细更多的内容参考:https://zhuanlan.zhihu.com/p/99150129

原文地址:https://www.cnblogs.com/lexus168/p/12707691.html