- 使用 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)
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()