Python 实例变量

Python 实例变量,python,function,variables,arguments,instance,Python,Function,Variables,Arguments,Instance,我想知道是否有可能在python中创建一个函数foo,以便 def calulate (self, input): input = #some stuff def foo2(self): self.calculate(self.var1) self.calculate(self.var2) 还是你一定要这么做 def calculation(self): output=#some stuff return output def foovar1(self

我想知道是否有可能在python中创建一个函数foo,以便

def calulate (self, input):
    input = #some stuff

def foo2(self):
    self.calculate(self.var1)
    self.calculate(self.var2)
还是你一定要这么做

def calculation(self):
    output=#some stuff
    return output
def foovar1(self):
    self.var1=self.calculation()
    self.var2=self.calculation()

我真的不想这样做,因为这将意味着在Python中创建更多的函数,您可以改变函数参数,但不能直接在调用方的作用域中重新绑定它们。您可以传递实例成员名称:

def foo(self, inputname):
    setattr(self, inputname, #some stuff)

def foo2(self):
    self.foo('var1')
    self.foo('var2')
或者,如果
self.var1
是一个可变对象,例如您可以编写的列表:

def foo (self, input):
    input[:] = #some stuff

def foo2(self):
    self.foo(self.var1)
    self.foo(self.var2)

这是因为您正在修改列表对象(通过指定给完整的切片),而不是重新绑定它(一个裸的
=
)。

另一个解决方案可能是使用特制的容器

class Container(object):
    def __init__(self, value=None):
        self.value = value
然后在另一个类中使用它:

def foo(self, container):
    container.value = ...

def foo2(self):
    self.foo(self.var1)
    self.foo(self.var2)

你的两个变种差别很大,我不明白/我想你应该用文字描述一下你想让这些片段做什么。@unwind不,他们没有,只是用了一些不同的名字reason@mgilson放松一下!!很抱歉,“self”一词通常与类方法相关联,但您谈论的是函数。确切地说,这是怎么回事?@WasiqKashkari当你写
input[:]=某物时,你正在修改名称
input
所指的对象;当您编写
input=something
时,您只需重新绑定名称
input
,以引用
something