zoukankan      html  css  js  c++  java
  • python类与对象-如何派生内置不可变类型并修其改实例化行为

    如何派生内置不可变类型并修其改实例化行为

    问题举例

    自定义一种新类型的元组,对传入的可迭代对象,我们只保留

    其中int类型且值大于0的元素,例如

    IntTuple([1, -1, 'abc', 6, ['x', 'y'], 3])  => (1, 6, 3)

    如何继承内置tuple实现IntTuple?

    分析

    对象的初始化有两个部分:__new__和__init__方法,

    对于tuple而言,它并没有__init__方法,直接在__new__中初始化

    解决思路

    继承内置tuple,并实现__new__,在其中修改实例化行为

    代码

    class IntTuple(tuple):
        def __new__(cls, iterable):
            # 过滤iterable
            f_it = (e for e in iterable if isinstance(e, int) and e > 0)
            return super().__new__(cls, f_it)
    
    int_t = IntTuple([1, -1, 'abc', 6, ['x', 'y'], 3])
    print(int_t)

    参考资料:python3实用编程技巧进阶

  • 相关阅读:
    java爬取Excel表格
    drf-view
    django--View
    tornado的Application的一些事儿
    tornado的路由分发
    线程和asyncio的比较
    GIL
    else的使用
    协程
    生成器代替迭代器
  • 原文地址:https://www.cnblogs.com/marton/p/10777848.html
Copyright © 2011-2022 走看看