简体   繁体   中英

In Python, can I define an instance method map() for the list class?

I was hoping to define an instance method map() or join() for the list class (for array). For example, for map() :

class list:
    def map(self, fn):
        result = []
        for i in self:
            result.append(fn(i))
        return result

print [1, 3, 5].map(str)

Is it possible in Python to do that for the list class? (if not, can the last line [1, 3, 5].map(str) be made to work?)

Your code creates a new variable called list , which hides the original. You can do a little better by inheriting:

class mylist(list):
    def map(self, fn):
        result = []
        for i in self:
            result.append(fn(i))
        return result

mylist([1, 3, 5]).map(str)

Note that it is not possible to override [] to generate anything other than a builtins.list


So that leaves monkeypatching the builtin. There's a module for that , forbiddenfruit , which in its own words:

may lead you to hell if used on production code.

If hell is where you're aiming for, then this is what you want:

from forbiddenfruit import curse
def list_map(self, fn):
    result = []
    for i in self:
        result.append(fn(i))
    return result
curse(list, "map", list_map)
print [1, 3, 5].map(str)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM