|
class Dog(object): def __init__(self,name):
self.name = name
def eat(self,food):
print ('%s is eating...' % self.name,food)
def bulk(self):
print ('%s is yelling.....' %self.name)
d = Dog('XiaoBai')
choice = input('>>:').strip()
if hasattr(d,choice):
func = getattr(d,choice)
func('Bone')
else:
# setattr(d,choice,bulk)
# d.talk(d)
setattr(d,choice,22) #建立一个新的、不存在的静态属性,赋予值22
print (getattr(d,choice))
执行结果:
>>:age #建立的静态属性名称为age,然后得到赋值22
22
执行结果:
>>:name #这里输入已存在的变量名
Traceback (most recent call last):
File "E:/Python/练习代码/A1.py", line 20, in <module>
func('Bone')
TypeError: 'str' object is not callable
#因为name的值已经通过func = getattr(d,choice)获取了,不能通过func('Bone')这样调用 |
|
|