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

2012-10-28 22:31:17 +08:00
 Brutal
比如 a = "abcd"
def format(str):
....print ','.join(list(str))

然后添加一个方法 a.format() ?
3624 次点击
所在节点    Python
4 条回复
binux
2012-10-28 22:50:43 +08:00
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
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
2012-10-28 23:24:43 +08:00
Python的builtin类型是无法改的,因为__dict__是只读的,只有自定义类型可以。
alsotang
2012-10-29 18:11:53 +08:00
用 Ruby 的话来说,叫做 “Python 的buildin 类型无法打开。”

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/51136

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX