### 7.7 栈 ```python class Stack: """ 后进先出来 """ def __init__(self): self.data_list = [] def push(self,val): """ 向栈中压入一个数据(入栈) """ self.data_list.append(val) def pop(self): """ 从栈中拿走一个数据 """ return self.data_list.pop() ``` ### 7.8 约束 ```python #约束子类中必须写send方法,如果不写,则调用的时候就会报错: class Interface(object): def send(self): raise NotImplementedError() class Message(Interface): def send(self): print('woshinibaba') class Email(Interface): def send(self): print('woshinimama') obj = Email() obj.send() ``` ### 7.9 反射 根据字符串的形式去某个对象中操作他的成员 - getattr(对象,字符串) 根据字符串的形式去某个对象中获取对象的成员 ```python class Foo: def __init(self,name): self.name = name obj = Foo('liujia') #获取变量 v1 = getattr(obj,'name') #获取方法 method_name = getattr(obj,'login') method_name() ``` - hasattr(对象,‘字符串’) 根据字符串的形式去某个对象中判断是否有该成员 ```python #!/usr/bin/env python # -*- coding:utf-8 -*- from wsgiref.simple_server import make_server class View(object): def login(self): return '登陆' def logout(self): return '等处' def index(self): return '首页' def func(environ,start_response): start_response("200 OK", [('Content-Type', 'text/plain; charset=utf-8')]) # obj = View() # 获取用户输入的URL method_name = environ.get('PATH_INFO').strip('/') if not hasattr(obj,method_name): return ["sdf".encode("utf-8"),] response = getattr(obj,method_name)() return [response.encode("utf-8") ] # 作用:写一个网站,用户只要来方法,就自动找到第三个参数并执行。 server = make_server('192.168.12.87', 8000, func) server.serve_forever() ``` - setattr(对象,'变量','值') 根据字符串的形式去某个对象中设置成员 ```python class Foo: pass obj = Foo: obj.k1 = 999 setattr(obj,'k1',123) print(obj.k1) ``` - delattr(对象,'变量') 根据字符串的形式去某个对象中伸出成员 ```python class Foo: pass obj = Foo() obj.k1 = 999 delattr(obj,'k1') print(obj.k1) ``` - python一切皆对象 - 包 - py文件 - 类 - 对象 python一切皆对象,所以以后想要通过字符串的形式操作内部成员都可以通过反射的机制实现 ### 7.10 模块:importlib 根据字符串的形式导入模块 ```pythn 模块 = importlib.import_module('utlis.redis') ```