zoukankan      html  css  js  c++  java
  • Day24

    内置函数

    __str__  __repr__

    当需要使用__str__的场景时找不到 __str__就找__repr__
    当需要使用__repr__的场景时找不到__repr__的时候就找父类的repr
    双下repr是双下str的备胎

    class List:
        def __init__(self,*args):
            self.l=list(args)
        def __str__(self):
            return '[%s]' %(','.join([str(i) for i in self.l]))
    l=List(1,2,3,4,5)
    print(l)        #l.__str__() object类中的__str__就是返回一个数据的内存地址
    print(str(l))
    print('%s'%l)
    # print(obj)   的结果 是 obj.__str__()的结果
    # str(obj)   的结果 也是 obj.__str__()的结果
    # '%s'%obj   的结果 也是 obj.__str__()的结果
    View Code
    class Teacher:
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def __str__(self):
            return "Teacher's object %s"%self.name
        def __repr__(self):
            return 'repr function %s'%self.name
    a = Teacher('alex',80)
    b = Teacher('egon',80)
    print(a)
    print(b)
    def repr(obj):
        return obj.__repr__()
    
    print(repr(a))   # 函数  打印repr的返回值
    print(a.__repr__())
    print('%r'%a)
    print(str(a))   # 函数 打印str函数的返回值
    # repr(obj)的结果和obj.__repr__()是一样的
    # '%r'%(obj)的结果和obj.__repr__()是一样的
    View Code
    # repr(1)
    # repr('1')
    # 因为 class int
    # 和class str
    #  中的__repr__方法不一样
    # class int:
    #     def __repr__(self):
    #         return str(1)
    
    # class str2:
    #     def __repr__(self):
    #         return "'%s'"%str(1)
    
    # a = int()
    # b = str2()
    # print(repr(a))
    # print(repr(b))
    View Code

    len() obj.__len__() 返回值是一致的
    len() 的结果是依赖 obj.__len__()
    hash() 的结果是依赖 obj.__hash__()

    str() 的结果是依赖 obj.__str__()
    print(obj) 的结果是依赖 obj.__str__()
    %s 的结果是依赖 obj.__str__() # 语法糖

    repr() 的结果是依赖 obj.__repr__()
    %r 的结果是依赖 obj.__repr__()

    repr是str的备胎

    __str__
    __repr__ 一定是选择repr

    __format__

    class A:
        def __init__(self,name,school,addr):
            self.name = name
            self.school = school
            self.addr = addr
        def __format__(self,format_spec):
            return format_spec.format(obj=self)
    
    
    a = A('大表哥','oldboy','沙河')
    format_spec = '{obj.name}-{obj.addr}-{obj.school}'
    print(format(a,format_spec))
    View Code
    format_dict={
        'nat':'{obj.name}-{obj.addr}-{obj.type}',#学校名-学校地址-学校类型
        'tna':'{obj.type}:{obj.name}:{obj.addr}',#学校类型:学校名:学校地址
        'tan':'{obj.type}/{obj.addr}/{obj.name}',#学校类型/学校地址/学校名
    }
    class School:
        def __init__(self,name,addr,type):
            self.name=name
            self.addr=addr
            self.type=type
    
        def __format__(self, format_spec):   #format_spec = 'nat'
            if not format_spec or format_spec not in format_dict:
                format_spec='nat'
            fmt=format_dict[format_spec]     #'{obj.name}-{obj.addr}-{obj.type}'
            return fmt.format(obj=self)     #'{obj.name}-{obj.addr}-{obj.type}'.format(obj=self)
    
    s1=School('oldboy1','北京','私立')
    print(format(s1,'nat'))  #s1.__format__('nat')
    print(format(s1,'tna'))
    print(format(s1,'tan'))
    print(format(s1,'asfdasdffd'))
    View Code

    __call__

    #__call__
    class Teacher:
        def __call__(self):
            print(123)
        def call(self):print(13)
    t = Teacher()
    t.call()
    t()   # 对象名() 相当于调用类内置的__call__
    # 一个对象是否可调用 完全取决于这个对象对应的类是否实现了__call__
    print(callable(Teacher))
    print(callable(t))
    View Code

    __eq__

    # == 是由__eq__的返回值来决定的
    class A:
        def __eq__(self, other):
            if self.__dict__ == other.__dict__:
                return True
    # __eq__()
    a = A()
    a.name = 'alex'
    b = A()
    b.name = 'egon'
    print(a.__dict__)
    print(b)
    print(a == b)
    View Code

    __del__

    # __del__ 析构方法:  在删除一个对象的时候做一些首尾工作
    class A:
        def __init__(self):
            self.f = open('文件','w')
        def __del__(self):
            self.f.close()
            print('执行我啦')
    a = A()
    del a
    print('aaa')
    View Code

    __new__

    __new__ 构造方法
    实例化的时候
    创造对象的过程 __new__
    __init__ 初始化

    # 设计模式 —— 单例模式
    # 单例模式 就是 一个类 只能有一个实例
    class B:
        __instance = None
        def __new__(cls, *args, **kwargs):
            if cls.__instance is None:
                obj = object.__new__(cls)
                cls.__instance = obj
            return cls.__instance
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def func(self):
            print(self.name)
    a = B('alex',80)
    b = B('egon',20)
    print(a)
    print(b)
    print(a.name)
    print(b.name)
    View Code

    __item__

    class Foo:
        def __init__(self,name):
            self.name=name
    
        def __getitem__(self,item):
            return  self.__dict__[item]
    
        def __setitem__(self, key, value):
            self.__dict__[key]=value
    
        def __delitem__(self, key):
            print('del obj[key]时,我执行')
            self.__dict__.pop(key)
    
    f = Foo('alex')
    # f.name = ...
    print(f['name'])    # f.__getitem__('name')
    f['age']  = 18      # 赋值
    print(f.age)         # 自带的语法
    print(f['age'])     # 修改
    f['age']  = 80
    print(f['age'])     # 通过实现__getitem__得到的
    del f['age']
    print(f.age)         # 删除
    View Code
    class Foo:
        def __init__(self,name):
            self.name=name
        def __delattr__(self, item):
            print('del obj.key时,我执行')
            self.__dict__.pop(item)
    f = Foo('alex')
    del f.name     #相当于执行了__delattr__
    # delattr(f,'name')
    print(f.__dict__)
    View Code

    推荐书籍

    核心编程 第2版
    核心编程 第3版
    流畅的python
    数据结构与算法 python 机械工业出版社

  • 相关阅读:
    HDOJ 4747 Mex
    HDU 1203 I NEED A OFFER!
    HDU 2616 Kill the monster
    HDU 3496 Watch The Movie
    Codeforces 347A A. Difference Row
    Codeforces 347B B. Fixed Points
    Codeforces 372B B. Hungry Sequence
    HDU 1476 Sudoku Killer
    HDU 1987 How many ways
    HDU 2564 词组缩写
  • 原文地址:https://www.cnblogs.com/a352735549/p/8884764.html
Copyright © 2011-2022 走看看