• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

Python学习笔记:day22 栈、顺序查找&可迭代对象&约束+异常+反射

开发技术 开发技术 3天前 6次浏览

今日内容

  • 讲作业
  • 可迭代对象
  • 约束 + 异常
  • 反射

内容详细

1.作业

1.1代码从上到下执行

print('你好')

def func():
    pass
func()
class Foo:
    x = 1
    def func(self):
        pass
Foo.x
class Foo:
    print('你好')
    def func(self):
        pass
clas Foo:
    x = 1
    def func(self):
        pass
    class Meta:
        y = 123
        def show(self):
            pass
clas Foo:
    print('你')
    x = 1
    def func(self):
        pass
    class Meta:
        print('好')
        y = 123
        def show(self):
            pass
2.看代码写结果
class Foo(object):

    def __init__(self, age):
        self.age = age

    def display(self):
        print(self.age)

data_list = [Foo(8), Foo(9)]
for item in data_list:
    print(item.age, item.display())
    
###
8
8 None
9
9 None
3.看代码写结果
class Base(object):
    def __init__(self,a1):
        self.a1 = a1
        
    def f2(self,arg):
        print(self.a1,arg)
        
class Foo(Base):
    def f2(self,arg):
        print('666')
        
obj_list = [Base(1),Foo(2),Foo(3)]
for obj in obj_list:
	obj.f2('alex')
    
###
1 alex
666
666
4.看代码写结果
class StarkConfig(object):

    def __init__(self,num):
        self.num = num

    def changelist(self,request):
        print(self.num,request)

class RoleConfig(StarkConfig):

    def changelist(self,request):
        print('666')

config_obj_list = [StarkConfig(1),StarkConfig(2),RoleConfig(3)]
for item in config_obj_list:
    print(item.num)
    
###
1
2
3
5.看代码写结果
class StarkConfig(object):
    def __init__(self,num):
        self.num = num
    def changelist(self,request):
        print(self.num,request)

class RoleConfig(StarkConfig):
    pass

config_obj_list = [StarkConfig(1),StarkConfig(2),RoleConfig(3)]
for item in config_obj_list:
    item.changelist(168)

###
1 168
2 168
3 168
6.看代码写结果
class StarkConfig(object):
    def __init__(self,num):
        self.num = num
    def changelist(self,request):
        print(self.num,request)

class RoleConfig(StarkConfig):
    def changelist(self,request):
        print(666,self.num)

config_obj_list = [StarkConfig(1),StarkConfig(2),RoleConfig(3)]
for item in config_obj_list:
    item.changelist(168)
    
###
1 168
2 168
666 3
7.看代码写结果
class StarkConfig(object):

    def __init__(self,num):
        self.num = num

    def changelist(self,request):
        print(self.num,request)

    def run(self):
        self.changelist(999)

class RoleConfig(StarkConfig):

    def changelist(self,request):
        print(666,self.num)

config_obj_list = [StarkConfig(1),StarkConfig(2),RoleConfig(3)]
config_obj_list[1].run()
config_obj_list[2].run()
8.看代码写结果
class StarkConfig(object):

    def __init__(self,num):
        self.num = num

    def changelist(self,request):
        print(self.num,request)

    def run(self):
        self.changelist(999)

class RoleConfig(StarkConfig):

    def changelist(self,request):
        print(666,self.num)


class AdminSite(object):
    def __init__(self):
        self._registry = {}

    def register(self,k,v):
        self._registry[k] = v

site = AdminSite()
print(len(site._registry)) 
site.register('range',666)
site.register('shilei',438)
print(len(site._registry))

site.register('lyd',StarkConfig(19))
site.register('yjl',StarkConfig(20))
site.register('fgz',RoleConfig(33))

print(len(site._registry))
print(site._registry)
9.看代码写结果
class StarkConfig(object):

    def __init__(self,num):
        self.num = num

    def changelist(self,request):
        print(self.num,request)

    def run(self):
        self.changelist(999)

class RoleConfig(StarkConfig):

    def changelist(self,request):
        print(666,self.num)

class AdminSite(object):
    def __init__(self):
        self._registry = {}

    def register(self,k,v):
        self._registry[k] = v

site = AdminSite()
site.register('lyd',StarkConfig(19))
site.register('yjl',StarkConfig(20))
site.register('fgz',RoleConfig(33))
print(len(site._registry)) # 3

for k,row in site._registry.items():
    row.changelist(5)
10.看代码写结果
class StarkConfig(object):

    def __init__(self,num):
        self.num = num

    def changelist(self,request):
        print(self.num,request)

    def run(self):
        self.changelist(999)

class RoleConfig(StarkConfig):

    def changelist(self,request):
        print(666,self.num)

class AdminSite(object):
    def __init__(self):
        self._registry = {}

    def register(self,k,v):
        self._registry[k] = v

site = AdminSite()
site.register('lyd',StarkConfig(19))
site.register('yjl',StarkConfig(20))
site.register('fgz',RoleConfig(33))
print(len(site._registry)) # 3

for k,row in site._registry.items():
    row.run()
11.看代码写结果
class UserInfo(object):
    pass

class Department(object):
    pass

class StarkConfig(object):
    def __init__(self,num):
        self.num = num
    def changelist(self,request):
        print(self.num,request)
    def run(self):
        self.changelist(999)

class RoleConfig(StarkConfig):
    def changelist(self,request):
        print(666,self.num)

class AdminSite(object):
    def __init__(self):
        self._registry = {}
    def register(self,k,v):
        self._registry[k] = v(k)

site = AdminSite()
site.register(UserInfo,StarkConfig)
site.register(Department,StarkConfig)
print(len(site._registry))
for k,row in site._registry.items():
    row.run()
12.看代码写结果
class F3(object):
    def f1(self):
        ret = super().f1()
        print(ret)
        return 123
    
class F2(object):
    def f1(self):
        print('123')
        
class F1(F3, F2):
	pass

obj = F1()
obj.f1()
13.看代码写结果
class Base(object):
    def __init__(self,name):
        self.name = name
        
class Foo(Base):
    def __init__(self,name):
        super().__init__(name)
        self.name = "于大爷"
        
obj1 = Foo('alex')
print(obj1.name)

obj2 = Base('alex')
print(obj2.name)

14.看代码写结果
class Base(object):
    pass

class Foo(Base):
    pass


obj = Foo()

print(type(obj) == Foo)
print(type(obj) == Base)
print(isinstance(obj,Foo))
print(isinstance(obj,Base))
15.看代码写结果
class StarkConfig(object):
    def __init__(self, num):
        self.num = num
    def __call__(self, *args, **kwargs):
        print(self.num)
class RoleConfig(StarkConfig):
    def __call__(self, *args, **kwargs):
        print(self.num)

v1 = StarkConfig(1)
v2 = RoleConfig(11)

v1() 
v2()
16.看代码写结果
class StarkConfig(object):
    def __init__(self, num):
        self.num = num
    def run(self):
        self()
    def __call__(self, *args, **kwargs):
        print(self.num)
        
class RoleConfig(StarkConfig):
    def __call__(self, *args, **kwargs):
        print(345)
    def __getitem__(self, item):
        return self.num[item]
    
v1 = RoleConfig('alex')
v2 = StarkConfig("wupeiqi")

print(v1[1])
print(v2[2]())
17.补全代码
class Context:
	pass

with Context() as ctx:
    ctx.do_something()
18.补全代码
class Stack(object):
    def __init__(self):
        self.data_list = []
        
    def push(self,val):
        pass
    
    def pop(self):
        pass
    
    
obj = Stack()
# 调用push方法,将数据加入到data_list中。
obj.push('alex')
obj.push('武沛齐')
obj.push('金老板')

# 调用pop讲数据从data_list获取并删掉,注意顺序(按照后进先出的格式)
v1 = obj.pop() # 金老板
v2 = obj.pop() # 武沛齐
v3 = obj.pop() # alex

# 请补全Stack类中的push和pop方法,将obj的对象维护成 后进先出 的结构。

###
class Stack(object):
    '''
    后进先出
    '''
    def __init__(self):
        self.data_list = []

    def push(self, val):
        '''
        向栈中压入一个数据(入栈)
        :param val:
        :return:
        '''
        self.data_list.append(val)

    def pop(self):
        '''
        从栈中拿走一个数据(出栈)
        :return:
        '''
        return self.data_list.pop()

obj = Stack()
obj.push('alex')
obj.push('eric')
obj.push('杀杀杀')

v1 = obj.pop()
print(v1)
v2 = obj.pop()
print(v2)
v2 = obj.pop()
print(v2)


class Stack(object):
    '''
    后进先出
    '''
    def __init__(self):
        self.data_list = []

    def push(self, val):
        '''
        向栈中压入一个数据(入栈)
        :param val:
        :return:
        '''
        self.data_list.insert(0,val)

    def pop(self):
        '''
        从栈中拿走一个数据(出栈)
        :return:
        '''
        return self.data_list.pop(0)
19.如何主动触发一个异常
20.看代码写结果
def func(arg):
    try:
        int(arg)
	except Exception as e:
        print('异常')
	finally:
        print('哦')
        
func('123')
func('二货')

2.可迭代对象

表象:可以被for循环对象就可以成为是可迭代对象:’X’,[11,2],{}…

class Foo:
    pass
obj = Foo()

如何让一个对象变成可迭代对象?

在类中实现__ iter __方法且返回一个迭代器(生成器)

class Foo:
    def __iter__(self):
        return iter([1,2,3,4])
obj = Foo()
###
class Foo:
    def __iter__(self):
        yield 1
        yield 2
        yield 3
        yield 4
obj = Foo()

记住:只要能被for循环就是去看他内部的iter方法

3.约束

# 约束子类中必须写send方法,如果不写,则调用时就会抛出NotImplementedError()
class Interface(object):
    def send(self):
        raise NotImplementedError()
        
class Message(Interface):
    def send(self):
        print('发送短信')
        
class Email(Interface):
    def send(self):
        print('发送邮件')
class Message(object):
    def message(self):
        print('发短信')
        
  	def email(self):
        print('邮件')
        
    def wechat(self):
        print('微信')
        
obj = Message()
obj.msg()
obj.email()
obj.wechat()
class BaseMessage(object):
    def send(self,a1):
        raise NotImplementedError('子类中必须有send方法')
class Msg(BaseMessage):
    def send(self):
        pass
class Email(BaseMessage):
    def send(self):
        pass
class Wechat(BaseMessage):
    def sendt(self):
        pass
class DingDing(BaseMessage):
    def send(self):
        print('钉钉')
obj = Msg()
obj.send()

4.反射

根据字符串的形式去某个对象中操作 他的成员

  • getattr(对象,’字符串’),根据字符串的形式去某个对象中 获取 对象的成员

    class Foo(object):
        def __init__(self,name):
            self.name = name
    obj = Foo('alex')
    
    #获取变量
    v1 = getattr(obj,'name')
    #获取方法
    method_name = getattr(obj,'login')
    method_name()
    
  • hasattr(对象,’字符串’) 根据字符串的形式去某个对象中判断是否有该成员

    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')]
        print(method_name)
        response = getattr(obj,method_name)()
        return [response.encode('utf-8')]
    
    #作用:写一个网站,用户只要来访问,就自动找到第三个参数并执行
    server = make_server('127.0.0.1',8000,func)
    server.serve_forever()
    
  • setattr(对象,’变量’,’值’) 根据字符串的形式去某个对象中 设置 成员

    class Foo:
        pass
    
    obj = Foo()
    obj.k1 = 999
    setattr(obj,'k1',123)  #obj.k1 = 123
    print(obj.k1)
    
  • delattr(对象,’变量’,’值’) 根据字符串的形式去某个对象中 删除 成员

    class Foo:
        pass
    
    obj = Foo()
    obj.k1 = 999
    print(obj.k1)
    delattr(obj,'k1')
    print(obj.k1)
    
class Foo(object):
    def __init__(self,name):
        self.name = name
        
obj = Foo('alex')
v1 = obj.name
v1 = getattr(obj,'name')

obj.name = 'eric'
setattr(obj,'name','eric')
class Foo(object):
    def login(self):
        pass
    def register(self):
        pass

obj = Foo()
func_name = input('请输入方法名')  #login
getattr(obj,func_name)()
'''
obj = Foo()
obj.login()
method_name = getattr(obj,'login')
method_name()

obj.register()
method_name = getattr(obj,'register')
method_name()
'''

Python一切皆对象

所以以后想要通过字符串的形式操作其内部成员都可以通过反射的机制实现

  • py文件
  • 对象

5.模块:importlib

根据字符串的形式导入模块。

模块 = importlib.import_module('utls.redis')

Python学习笔记:day22 栈、顺序查找&可迭代对象&约束+异常+反射

# import utils.redis
# from utils import redis
import importlib
middleware_classes = [
    'utils.redis.Redis',
    'utils.mysql.Mysql',
    'utils.moggo.Mongo'

]
for path in middleware_classes:
    module_path,func_name = path.rsplit('.',maxsplit=1)
    module_object = importlib.import_module(module_path)
    cls = getattr(module_object,func_name)
    obj = cls()
    obj.connect()


# #用字符串的形式导入模块
# redis = importlib.import_module('utls.redis')
# # redis.func()
# #用字符串的形式去对象(模块)找到他的成员
# getattr(redis,'func')()

喜欢 (0)