• Python面向对象进阶(二)


    Python面向对象进阶2.html


    title: Python 面向对象进阶2
    tags: Python

     

    1 setitem getitem delitem

    把 对象操作属性模拟字典格式

    class Foo:
        def __init__(self,name):
            self.name=name
        def __getitem__(self, item):
            return self.__dict__[item]  # getitem 通过return返回
        def __setitem__(self, key, value):
            self.__dict__[key]=value     # 真正操作的是字典中的
        def __delitem__(self,key):
            # self.__dict__.pop[key]  # 把字典中的删除
            self.__dict__.pop(key)  # pop是个函数
    
    f=Foo('aaa')  # 实例化
    print(f['name']) # 这是getitem
    f['age']=18  # setitem
    print(f.__dict__)
    

    打印结果:
    {‘name’: ‘aaa’, ‘age’: 18}

    f=Foo('aaa')
    print(f['name'])
    f['age']=18
    del f['age']    # delitem
    del f['name']
    print(f.__dict__)  # 通过查看对象的名称空间可
    

    结果:

    2 _slots_

    slots是一个类变量,变量的值可以是列表、字典、字符串、可迭代对象,用的是类的名称空间,是共享的,对象没有自己的名称空间,省内存

    class People:
        __slots__=['x','y','z']  #设置相应的属性
    p=People()
    print(People.__dict__)
    p.x=1
    p.y=2
    p.z=3
    print(p.x,p.y,p.z)
    # print(p.__dict__)
    p1=People()
    p1.x=11
    p1.y=21
    p1.z=31
    print(p1.x,p1.y,p1.z)
    

    结果:
    1 2 3
    11 21 31

    slots应用:字典会占用大量内存,如果一个类的属性很少,但是有很多类,为了节省内存可以使用slots代替dict

    3 __next和 ___iter__ 实现迭代器协议

    可迭代对象内置iter方法,可迭代对象赋值就是一个迭代器,迭代器可以使用next方法

    from collections import Iterator,Iterable
    class Foo:
        def __init__(self,start):
            self.start=start
        def __iter__(self):
            return self
        def __next__(self):
            if self.start > 10:
                raise StopIteration
            n = self.start
            self.start+=1
            return n
    
    f=Foo(5)
    # print(next(f))
    for i in f:
        print(i)
    

    4 _doc_

    class Foo:
        '这是描述信息'
        pass
    print(Foo.__doc__)    # 打印的结果就是函数的注释信息
    

    无法继承

    class Foo:
        '这是描述信息'
        pass
    class Bar(Foo):
        pass
    print(Bar.__dic__)
    

    结果:
    type object ‘Bar’ has no attribute ‘dic

    5 _module 和 __class__

    module 表示当前操作的对象在那个模块

    class 表示当前操作的对象的类是什么

    class Foo:
        '这是描述信息'
        pass
    class Bar(Foo):
        pass
    # print(Bar.__dic__)
    b=Bar()
    print(b.__module__)
    print(b.__class__)
    print(Bar.__class__)
    print(Foo.__class__)
    

    结果:
    main
    class ‘main.Bar’>
    class ‘type’>
    class ‘type’>

    6 _del_ 析构方法

    但对象在内存中被释放时,自动触发_del_

    class Foo(object):
        """docstring for Foo"""
        def __del__(self):
            print("zhi xing ")
    f1 = Foo()
    del f1
    print('----')
    

    文件操作

    class Open:
        def __init__(self,filepath,mode='r',encoding='utf-8'):
            self.x = open(filepath,mode=mode,encoding=encoding)
            # self.x = open(filepath,mode=mode,encoding=encoding)
            self.filepath =filepath
            self.mode=mode
            self.encoding=encoding
        def write(self,line):
            self.x.write(line)
        def __getattr__(self, item):
            return getattr(self.x,item)
        def __del__(self):
            self.x.close()
    f=Open('a.txt','w')
    del f
    

    7 __enter__ 和 __exit__上下文管理协议

    上下文管理协议,即with语句,为了让一个对象兼容with语句必须在对象中声明enteriter

  • 相关阅读:
    php上传进度条
    array_combine — 创建一个数组,用一个数组的值作为其键名,另一个数组的值作为其值
    password_hash 与 password_verify
    这是一个微信带参数的二维码,自定义菜单,与图文回复
    go to 语句用起来还是挺方便的
    初次使用海豚php的一个例子
    图片下载
    一对一的关联映射
    延迟加载
    proxy和proxy-no的策略取值区别
  • 原文地址:https://www.cnblogs.com/Python666/p/6763763.html
Copyright © 2020-2023  润新知