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)'
{single way to add一个子类
不,不能在
list
对象上添加或删除属性,Python2和Python3中都不能。你知道吗最多可以在另一个实例中包装这样的对象,该实例实现与列表相同的属性和方法,但将对这些属性和方法的访问传递给包装的listobject。你知道吗
该包装器可以用^{} class 实现:
演示:
相关问题 更多 >
编程相关推荐