使用作为方法变量的函数影响类变量



假设我有一个类,其方法将函数作为参数。有没有办法让这个函数改变类变量?

def f():
    # something here to change MyClass.var
class MyClass:
    def __init__():
        self.var = 1
    def method(self, func):
        #does something
        func()
obj = MyClass()
obj.method(f)
print(obj.var)

只需将类的内部引用 - self - 传递到函数中:

>>> class Class:
        def __init__(self):
            self.var = 1
        def method(self, func):
            func(self)
>>> def func(inst):
        inst.var = 0

>>> cls = Class()
>>> cls.var
1
>>> cls.method(func)
>>> cls.var
0
>>> 

在相关的旁注中,我认为实际上使您的函数成为类的方法会更清晰,更清晰:

>>> from types import MethodType
>>> 
>>> def func(self):
        self.var = 0

>>> class Class:
        def __init__(self):
            self.var = 1

>>> cls = Class()
>>> cls.var
1
>>> cls.func = MethodType(func, cls)
>>> cls.func()
>>> cls.var
0
>>> 

这应该有效:

def f(obj):
    obj.var = 2
class MyClass:
    def __init__(self):
        self.var = 1
    def method(self, func):
        # does something
        func(self)
obj = MyClass()
obj.method(f)
print(obj.var)  # --> 2

由于函数 f 是在类范围之外定义的,因此它无法访问类变量。但是,您可以将类变量作为参数传递给 f,在这种情况下,它将能够对其执行任何操作。

def f(x):
    return x**2  # just for the demonstration. Will square the existing value\
  # of the class variable

class MyClass:
    def __init__(self):
        self.var = 2
    def method(self, func):
        #does something
        self.var = func(self.var)
obj = MyClass()
obj.method(f)
print(obj.var)   
>>> 4

最新更新