1

我有这个功能(包括描述):

def deep_list(x):
    """fully copies trees of tuples to a tree of lists.
    deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]"""
    if type(x)!=type( () ):
        return x
    return map(deep_list,x)

我想将该函数插入到我制作的函数类中,所以我需要self在开头添加函数参数。

我的问题是这样的:如何以正确的方式self在 'map' 函数的末尾插入deep_list

4

2 回答 2

4

取决于x与您的班级的关系。

一种方法是使函数成为静态方法。这可能是最不可能的

@staticmethod
def deep_list(x):
    """fully copies trees of tuples to a tree of lists.
       deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]"""
    if type(x)!=type( () ):
        return x
    return map(deep_list,x)

如果你的意思是对一个属性进行操作,那么就这样做吧

def deep_list(self):
    """fully copies trees of tuples to a tree of lists.
       deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]"""
    if type(self.x)!=type( () ):
        return self.x
    return map(deep_list, self.x)

最后,如果您要继承list或制作类似类的序列,您可以只使用self

def deep_list(self):
    """fully copies trees of tuples to a tree of lists.
       deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]"""
    if type(self)!=type( () ):
        return self
    return map(deep_list, self)
于 2012-11-25T23:58:34.727 回答
1

我不确定我是否理解您的要求,但是如果您映射绑定方法,则 self 将已包含在内:

>>> class Foo(object):
...     def func(self, x):
...         return x + 2
>>> f = Foo()
>>> map(f.func, [1, 2, 3])
[3, 4, 5]
于 2012-11-25T23:56:20.840 回答