ANDREYDEN
ANDREYDEN

Reputation: 148

Influencing class variables with functions that are method's variables

Say I have a class with a method that takes a function as an argument. Is there any way to make this function change inclass variables?

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)

Upvotes: 0

Views: 53

Answers (3)

Chris
Chris

Reputation: 22963

Simply pass the internal reference of your class - self - into the function:

>>> 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
>>> 

On a related side note, I'd argue that it'd be cleaner and clearer to actually make your function a method of your class:

>>> 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
>>> 

Upvotes: 6

Neel
Neel

Reputation: 369

Since the function f is defined outside the scope of the class, it can not access the class variable. However you can pass the class variable as an argument to f, and in that case it will be able to do any operation on it.

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

Upvotes: 0

sciroccorics
sciroccorics

Reputation: 2427

This should work:

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

Upvotes: 0

Related Questions