反射
反射就是通过字符串来操作类或者对象的属性
反射本质就是在使用内置函数,其中反射有以下四个内置函数:
1. hasattr
2. getattr
3. setattr
4. delattr
class People:
country = 'China'
def __init__(self, name):
self.name = name
def eat(self):
print('%s is eating' % self.name)
peo1 = People('egon')
print(hasattr(peo1, 'eat')) # peo1.eat
True
print(getattr(peo1, 'eat')) # peo1.eat
<bound method People.eat of <__main__.People object at 0x104e25cf8>>
print(getattr(peo1, 'xxxxx', None))
None
setattr(peo1, 'age', 18) # peo1.age=18
print(peo1.age)
18
print(peo1.__dict__)
{'name': 'egon', 'age': 18}
delattr(peo1, 'name') # del peo1.name
print(peo1.__dict__)
{'age': 18}
反射的应用
class Ftp:
def __init__(self, ip, port):
self.ip = ip
self.port = port
def get(self):
print('GET function')
def put(self):
print('PUT function')
def run(self):
while True:
choice = input('>>>: ').strip()
if choice == 'q':
print('break')
break
# print(choice, type(choice))
# if hasattr(self, choice):
# method = getattr(self, choice)
# method()
# else:
# print('输入的命令不存在')
method = getattr(self, choice, None)
if method is None:
print('输入的命令不存在')
else:
method()
conn = Ftp('1.1.1.1', 23)
conn.run()
>>>: get
GET function
>>>: put
PUT function
>>>: q
break