• 魔术方法


    一、简介

    在Python中,所有以“__”双下划线包起来的方法,都统称为“Magic Method”(魔术方法),例如类的初始化方法 __init__ ,Python中所有的魔术方法均在官方文档中有相应描述

    这里有一篇博客讲得很详细,可以参考下:cnblogs.com/nmb-musen/p/10861536.html

    二、with和上下文管理器

    上下文管理协议:包含__enter()__ 和__exit()__方法

    上下文管理器:支持“上下文管理协议对象”

    几乎所有的人知道“with open”,这就时一个典型的上下文管理的例子

    f = open('test.txt')  #f就是一个上下文管理器     
    print(dir(f))                         

    f中包含__enter()__ 和__exit()__方法,那么f就是一个上下文管理器

    下面我们来理清几个概念:

    1. 上下文表达式:with open('test.txt') as f:
    2. 上下文管理器:open('test.txt')
    3. f 不是上下文管理器,应该是资源对象

    如何自己顶一个一个上下文管理器:

    class Myclass(object):         
                                   
        def __enter__(self):       
            print('enter is running
            return 1               
                                   
        def __exit__(self, exc_type
            print('exit is running'
            return 2 
    
    def main():                     
        obj = Myclass()             
        with obj as o:              
            print('with is running')
    #执行:
    main()
    
    #输出结果:
    enter is running
    with is running
    exit is running

    不懂没关系,我们再来看一段代码:

    #自定义一个类不包含__enter__和__exit__方法
    class Base(object)
        pass          
    
    def main():                      
        obj = Base()                 
        with obj as o:               
            print('with is running')    
    #执行:
    main()   
    
    #输出结果:
    AttributeError: __enter__

    总结:在一个类里面实现了__enter()__ 和__exit()__方法,那么这个类就是一个上下文管理器,可以使用with调用

    三、常见的魔术方法:

    __str__方法:_str__方法需要返回一个字符串,当做这个对象的描写

    看下面一段代码:

    class MyClass(object):
        def __init__(self, name):
            self.name = name
    
        def __str__(self):
            return self.name
    
    
    def main():
        obj = MyClass('chenran')
        print(hasattr(obj, '__str__'))
        print(obj)
    #执行:
    main()
    
    #输出结果:
    True
    CHENRAN
  • 相关阅读:
    TOJ1017: Tour Guide
    tzcacm去年训练的好题的AC代码及题解
    Educational Codeforces Round 40 (Rated for Div. 2)
    AtCoder Regular Contest 092
    浙南联合训练赛20180318
    [Offer收割]编程练习赛50
    牛客练习赛13
    AtCoder Regular Contest 091
    Codeforces Round #470 (rated, Div. 2, based on VK Cup 2018 Round 1)
    csa Round #73 (Div. 2 only)
  • 原文地址:https://www.cnblogs.com/crdhm12040605/p/14136454.html
Copyright © 2020-2023  润新知