Python 给类动态的添加属性或者方法

  • 使用 hasattr ,getattr,setattr 。当然也可以在调用时删除属性和方法 (delattr):
  • example:
class Dog(object):
    def __init__(self,name):
        self.name = name
    def eat(self,food):
        print("%s id eating ..%s"%(self.name,food))

def bark(self):
    print("%s is yelling okok"% self.name)


d=Dog("hello")
choice = input("请输入你要添加的属性或者方法:").strip()


def addAttr():
    print("INFO: %s %s"%(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),addAttr.__name__))
    if hasattr(d,choice):
        if not isinstance(getattr(d,choice),str):
            func = getattr(d,choice)
            func("apple") #调函数
        else:
            val =getattr(d,choice) # 获取属性
            print(val)
    else:
        try:
            values = input("添加方法1,添加属性2:").strip()
            valu = input("请输入属性值或者方法名").strip()
            setattr(d,choice,eval(valu)) if values=="1" else setattr(d,choice,valu) # valu= d.choice
            val = getattr(d,choice)
            if isinstance(val,str):
                print(val)
            else:
                val(d)
                print(val.__name__)
        except Exception as e:
            print("ERROR:%s %s"%(e,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
addAttr()
发布了127 篇原创文章 · 获赞 25 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_44224529/article/details/103693918