V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
1989922yan
V2EX  ›  Python

len()在类中有什么特殊方法? len()一个实例,是 len 了什么的长度呢?

  •  
  •   1989922yan · 2014-12-02 14:03:54 +08:00 · 2700 次点击
    这是一个创建于 3446 天前的主题,其中的信息可能已经有所发展或是发生改变。
    >>> class A(dict): pass
    >>> aa = A()
    >>> len(aa)

    len()在类中有什么特殊方法? len()一个实例,是 len 了什么的长度呢?
    4 条回复    2014-12-02 16:32:47 +08:00
    lianghui
        1
    lianghui  
       2014-12-02 14:31:51 +08:00   ❤️ 2
    __len__ 方法
    aheadlead
        2
    aheadlead  
       2014-12-02 14:56:14 +08:00   ❤️ 1
    1L正解...
    staticor
        3
    staticor  
       2014-12-02 15:07:56 +08:00   ❤️ 1
    可参考http://stackoverflow.com/questions/2481421/difference-between-len-and-len 或者定义一个类后改写一下 __len__ 方法
    joshryo
        4
    joshryo  
       2014-12-02 16:32:47 +08:00   ❤️ 1
    len函数会去调用类的__len__方法,所以想要能用len函数,你定义类的时候都得写__len__方法
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2808 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 15:38 · PVG 23:38 · LAX 08:38 · JFK 11:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.