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
Brutal
V2EX  ›  Python

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

  •  
  •   Brutal · 2012-10-28 22:31:17 +08:00 · 3597 次点击
    这是一个创建于 4168 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如 a = "abcd"
    def format(str):
    ....print ','.join(list(str))

    然后添加一个方法 a.format() ?
    4 条回复    1970-01-01 08:00:00 +08:00
    binux
        1
    binux  
       2012-10-28 22:50:43 +08:00   ❤️ 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
       2012-10-28 23:08:56 +08:00
    @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  
       2012-10-28 23:24:43 +08:00   ❤️ 1
    Python的builtin类型是无法改的,因为__dict__是只读的,只有自定义类型可以。
    alsotang
        4
    alsotang  
       2012-10-29 18:11:53 +08:00
    用 Ruby 的话来说,叫做 “Python 的buildin 类型无法打开。”
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5442 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 08:37 · PVG 16:37 · LAX 01:37 · JFK 04:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.