我有这个函数(包括描述):
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
。
我的问题是这样的:如何在deep_list
末尾以正确的方式插入self
"map"功能?
取决于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)
我不确定我是否理解你在问什么,但是如果你映射一个绑定方法,self 已经包含在内:
>>> class Foo(object):
... def func(self, x):
... return x + 2
>>> f = Foo()
>>> map(f.func, [1, 2, 3])
[3, 4, 5]