是否可以向Python列表实例添加方法?

2024-04-26 02:51:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试“修补”列表的一个实例。请注意,这不是我的名单。我无法控制它的产生。据我所知,这在2.7中是不可能的。我说得对吗?在3.x里可能吗?你知道吗


Tags: 实例列表名单
2条回答

{single way to add一个子类

>>> import new
>>> L = ['f', 'o', 'o']
>>> M = type("list", (list, ), {})(L)
>>> M.bar = new.instancemethod(lambda self: self * 2, M)
>>> M.bar()
['f', 'o', 'o', 'f', 'o', 'o']

不,不能在list对象上添加或删除属性,Python2和Python3中都不能。你知道吗

最多可以在另一个实例中包装这样的对象,该实例实现与列表相同的属性和方法,但将对这些属性和方法的访问传递给包装的listobject。你知道吗

该包装器可以用^{} class实现:

try:
    # Python 2
    from UserList import UserList
except ImportError:
    # Python 3
    from collections import UserList

class ListWrapper(UserList):
    def extra_method(self):
        return """Hi! I'm an extra method on this "list" (wink, wink)"""

演示:

>>> some_list = ['foo', 'bar', 'baz']
>>> wrapped_list = ListWrapper(some_list)
>>> len(wrapped_list)
3
>>> wrapped_list[1]
'bar'
>>> wrapped_list.extra_method()
'Hi! I\'m an extra method on this "list" (wink, wink)'

相关问题 更多 >