标签:函数 put 内存 命令 print 执行 ice nbsp ase
1 class people(object): 2 def __init__(self, name, age): 3 self.name = name 4 self.age = age 5 6 def talk(self): 7 print(‘%s is talking ...‘%self.name) 8 p1 = people(‘zsq‘, 28) 9 choice = input(‘please inpute choice‘) 10 11 #hasattr当前对象中有对应该字符串名的方法或属性返回True否则返回False.# choice输入name/age/talk都会返回True否则返回False 12 if choice in (‘name‘, ‘age‘, ‘talk‘): 13 print(hasattr(p1, choice)) 14 else: 15 print(‘this choice not in hasattr‘) 16 17 #getattr方法返回该对象对应字符串参数方法的内存地址,加()就可以执行。# 如果字符串是对象的属性则直接返回属性值。 18 if choice in ( ‘talk‘, ): 19 getattr(p1, choice)() 20 elif choice in (‘name‘, ‘age‘): 21 a = getattr(p1, choice) 22 print(a) 23 24 #setattr(x, ‘y‘, v) setattr命令以后调用对象的choice方法时,直接调用test_setattr函数;不论对象是否原来有该方法 25 #setattr命令以后调用对象的choice属性时时,直接返回v的内存地址(对象)或者值(常量) 26 def test_setattr(): 27 print(‘this is test setattr‘) 28 29 if choice == ‘talk1‘: 30 setattr(p1, choice, test_setattr) 31 p1.talk() 32 elif choice == ‘name1‘: 33 setattr(p1, choice, ‘name_test‘) 34 print(getattr(p1, choice)) 35 #delattr 删除对象对应的属性或者方法 36 if choice == ‘age‘: 37 delattr(p1, choice) 38 print(p1.age)
标签:函数 put 内存 命令 print 执行 ice nbsp ase
原文地址:http://www.cnblogs.com/flags-blog/p/7896588.html