推荐学习书目
› 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
Brutal
V2EX  ›  Python

Python 可否添加类似于 JS 的原型函数?

  •  
  •   Brutal · Oct 28, 2012 · 5042 views
    This topic created in 5084 days ago, the information mentioned may be changed or developed.
    比如 a = "abcd"
    def format(str):
    ....print ','.join(list(str))

    然后添加一个方法 a.format() ?
    4 replies  •  1970-01-01 08:00:00 +08:00
    binux
        1
    binux  
       Oct 28, 2012   ❤️ 1
    builtin类型不知道怎么搞

    a = "abcd"
    def format(self, str):
    ....print ",".join(list(str))

    base = type("str", [type(a), ], {})
    base.format = format
    a = base(a)
    a.format("123")
    Brutal
        2
    Brutal  
    OP
       Oct 28, 2012
    @binux 这样的话就不用这么麻烦了,直接新建一个 class 就可以了

    >>> class cls:
    ... def __init__(self, value):
    ... self.value = value
    ...
    ... def format(self):
    ... print ','.join(self.value)
    ...
    ...
    ...
    >>> a=cls('sab')
    >>> a.format()
    s,a,b
    timonwong
        3
    timonwong  
       Oct 28, 2012   ❤️ 1
    Python的builtin类型是无法改的,因为__dict__是只读的,只有自定义类型可以。
    alsotang
        4
    alsotang  
       Oct 29, 2012
    用 Ruby 的话来说,叫做 “Python 的buildin 类型无法打开。”
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2858 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 10:31 · PVG 18:31 · LAX 03:31 · JFK 06:31
    ♥ Do have faith in what you're doing.