python定义一种新类型的元组
2024-09-05 12:26:50
# 定义一种新类型的元组,只保留int类型,切只大于0的元素
# 例如:IntTuple([1,-1,"abc",6,['x','y'],3])==>(1,6,3) # 解决方案:定义类IntTuple继承内置tuple,并实现__new__方法,修改实例行为 class IntTuple(tuple):
"""
__new__方法接受的参数虽然也是和__init__一样,但__init__是在类实例创建之后调用,而 __new__方法正是创建这个类实例的方法,其在__init__之前运行 依照Python官方文档的说法,__new__方法主要是当你继承一些不可变的class时(比如int, str, tuple), 提供给你一个自定义这些类的实例化过程的途径。还有就是实现自定义的metaclass。
"""
def __new__(cls, iterable):
g = (x for x in iterable if isinstance(x, int) and x > 0)
n = super(IntTuple, cls).__new__(cls, g)
print(n)
print("------")
return n # def __init__(self, iterable):
# print(self)
# super(IntTuple, self).__init__() t_list = [1, -1, "abc", 6, ['x', 'y'], 3]
t = IntTuple(t_list)
print(t)
参照:https://my.oschina.net/liuyuantao/blog/747164
最新文章
- PHP的学习--使用phar打包
- 防止别人ping自己的服务器
- kill 命令详解 系统信号
- 鸟哥的linux私房菜学习记录之开机流程、模块管理与Loader
- 15、C#基础整理(递归)
- 欧拉工程第53题:Combinatoric selections
- Android文字转语音
- Ext学习-高级组件介绍
- PHP引用(&;)详解
- c语言筛选质数
- 设计模式之桥接模式(Bridge)--结构模型
- 【1】【leetcode-92】 反转链表 II
- sqlserver存储过程sp_send_dbmail邮件(html)实际应用
- Linux内核如何装载和启动一个可执行程序(转)
- 面向对象 Java练习
- JDK(十)JDK1.7&;1.8源码对比分析【集合】ConcurrentHashMap
- 【课堂实验】Arrays和String单元测试
- Tensorboard教程:Tensorflow命名空间与计算图可视化
- lr11_Vugen_Genrial Options选项介绍:
- 查看postgre都有哪些语句占用CPU