类的专有方法(__len__)
方法 __ len 专有
2023-09-11 14:17:15 时间
# -*- coding: utf-8 -*- #python 27 #xiaodeng #http://www.imooc.com/code/6252 #类的专有方法(__len__) #如果一个类表现得像一个list,要获得有多少个元素,就得用len();要让len()函数正常工作,类必须提供一个特殊的方法__len__(),才能返回元素的个数 #案例01 class Fib(): def __init__(self, num): a, b, L = 0, 1, [] for i in range(num): L.append(a) a, b = b, a+b self.numbers = L def __str__(self): return str(self.numbers) def __len__(self): return len(self.numbers) f = Fib(10) print f print len(f) #案例02 class Students(): def __init__(self, *args): self.names = args def __len__(self): return len(self.names) ss = Students('Bob', 'Alice', 'Tim') print len(ss)
相关文章
- Could not set limit for ‘nofile’: Operation not permitted的处理方法
- 【PHP面向对象(OOP)编程入门教程】22.把对象串行化serialize()方法,__sleep()方法,__wakeup()方法
- 【PHP面向对象(OOP)编程入门教程】8.构造方法__construct()与析构方法__destruct()
- the attribute buffer size is too small 解决方法
- java数据类型转换的常见方法
- python正常时间和unix时间戳相互转换的方法
- 企业数据分析的架构和方法
- Qt通用方法及类库11
- python垃圾回收示例及__del__(self)方法的使用(它会在对象被垃圾回收前调用)
- PHP获取用户访问IP地址的5种方法
- linux学习:虚拟机VMware安装CentOS 7.4的方法
- Python中的魔术(双下划线'__xxx__')方法详解
- thinkphp在前端页面的js代码中可以使用 U方法吗? 可以使用模板变量如__URL__等吗?
- Go语言自学系列 | golang方法接收者类型
- C: integer overflow,隐式类型转换/整数加法溢出 解决方法示例;check_add_overflow;__builtin_add_overflow
- python中的类,对象,成员方法,构造方法,__init__,__lt__,__le__,__eq__
- __getattribute__的妙用,实现对象实例的“继承“与方法重载
- 无法定位程序输入点__gxx_personality_v0的一个解决方法