python中__init__ &自定义上下文管理器,优化封装

python中类中有构造方法__init__,通过__init__能在类对象实例化时初始化赋值

class Person:
    def __init__(self):
        self.has_head = True
    def query_person_head():
        if self.has_head:
            print('有脑子')
        else:
            print('没头了')
    def work(self):
        print('走一步')
#定义僵尸类,继承人
class Zombie(Person):
    def __init__(self):
        self.is_dead = True
    def eat(self):
        print('吃人吃人')
#实例化一个僵尸
z = Zombie()
z.eat()
#吃人吃人
z.work()
#走一步
z.query_person_head()
#'Zombie' object has no attribute 'has_head'

出现以上结果的原因是因为构造方法中的初始值无法继承
解决思路:通过super函数

def Zombie(Person):
    def __init__(self):
        super(Zombie,self).__init__()
    def eat(self):
        print('吃人吃人')
z = Zombie()
z.query_person_head()
#有脑子

自定义上下文管理器

自定义上下文管理器,可以封装一些例如文件读取,数据库连接等操作

#定义根资源类
class MyResource:
    def __enter__(self):
        print('connect to resource')
        return self
    def __exit__(self,exc_type,exc_val,exc_tb):
        print('close resource connection')
        if exc_type:
            print(exc_val)
        #True表示不向外部抛出异常,默认Flase
        return Ture
    def query(self):
        print('query data')

with MyResource() as resource:
    resource.query()
#resource接收__enter__方法的返回值

猜你喜欢

转载自blog.csdn.net/weixin_35993084/article/details/80612206