这是我要使用的代码。如果我将getset_pos用作函数而不是此处的方法,则效果很好。编辑:更正第6行(getset_pos现在为self.getset_pos);edit2:在末尾添加了对类的调用
class Main:
def __init__(self):
self.i = [5, 5]
self.o = []
self.getset_pos(self.i, self.o)
def getset_pos(self, input, output):
""" Takes the coord of an item and sets it equal to another item """
output = []
for numb in input:
output.append(numb)
print output
test = Main()
test
我可以让getset_pos()方法专门用于self.i和self.o变量,但是,我发现这更多的是我想要的:
class Main:
def __init__(self):
self.i = [5, 5]
self.o = []
def getset_pos(input, output):
output = []
for numb in input:
output.append(numb)
return output
getset_pos(self.i, self.o)
test = Main()
test
每当我调用此函数时,此函数将使我可以更轻松地将变量的值更新为另一个变量。我只需要在方法中调用它。
您不能对作为参数传入的引用执行赋值,并希望该赋值反映在方法之外。这个问题的答案将详细说明为什么。
一种更直接的方法是简单地使用self
引用,并跳过传递额外的参数。
class Main:
def __init__(self):
self.i = [5, 5]
self.o = []
self.getset_pos()
def getset_pos(self):
""" Takes the coord of an item and sets it equal to another item """
self.o = []
for numb in input:
self.o.append(numb)
print output
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句