标签:put 字符串 ice name choice 通过 login 判断 默认
# 反射:通过字符串来操作对象属性,类也是一样。 class Foo: def __init__(self, name): self.name = name def eat(self): print(‘%s is eating‘ % self.name) obj = Foo(‘egon‘) print(hasattr(obj, ‘eat‘)) # 判断对象是否有eat属性,有返回True print(getattr(obj, ‘age‘, None)) # 获取对象是否有age属性,没有返回设置的默认值None setattr(obj, ‘age‘, 18) # 当age不存在时候就是创建、存在就是需改 print(obj.__dict__) # {‘age‘: 18, ‘name‘: ‘egon‘} setattr(obj, ‘age‘, 180) print(obj.__dict__) # {‘age‘: 180, ‘name‘: ‘egon‘} #case class Ftp: def get(self): print(‘get‘) def put(self): print(‘put‘) def login(self): print(‘login‘) def run(self): while True: choice = input(‘>>:‘).strip() if hasattr(self, choice): method=getattr(self,choice) method() else: print(‘命令不存在‘) obj = Ftp() obj.run()
标签:put 字符串 ice name choice 通过 login 判断 默认
原文地址:https://www.cnblogs.com/yspass/p/9581326.html