反射我们以后会经常用到,这个东西实现了动态的装配,通过字符串来反射类中的属性和方法

反射函数

1、hasarttr(obj,name_str)

作用:判断一个对象obj中是否有对应的name_str字符串的属性或者方法

class Dog(object):
  
    def __init__(self,name):
        self.name = name
  
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
  
d = Dog("shabi")
choice = input(">>>:").strip()
  
print(hasattr(d,choice))  #obj中是否有对应的choice字符串的属性或者方法
  
#输出
>>>:name  #输入对象存在属性
True
>>>:eat  #输入对象存在的方法
True
View Code

相关文章:

  • 2021-09-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-18
  • 2018-10-18
猜你喜欢
  • 2021-11-17
  • 2022-12-23
  • 2021-05-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-22
相关资源
相似解决方案