Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can python functions defined inside class methods access self?

Tags:

python

Taking this class as an example:

class MyClass(object):
    def __init__(self):
        self.attribute = 4

    def my_method(self):
        def my_fun(arg1, arg2):
            self.attribute = 7

        pass

should my_fun be allowed to access and change self.attribute ?

I can see that my editor does not colour self inside my_fun.

This is what I am trying to implement: my_method should call an external function that requires a callback taking two arguments, arg1 and arg2. I would like to extend the functionality by allowing this callback to use variables declared inside my_method, and also make the my_fun callback write some debugging info to self.log. I am not quite sure if this is the right design for this type of problem.

like image 974
George Avatar asked Feb 10 '19 22:02

George


Video Answer


1 Answers

Yes. self is just another variable. It's python automatically passing in the reference to the instance as the first argument. Nothing more.

Your inner function will be able to access self as if it were a regular function that accesses a regular object.

class MyClass(object):
    def __init__(self):
        self.attribute = 4

    def my_method(self):
        def my_fun():
            self.attribute = 7

        return my_fun

a = MyClass()
a.my_method()()
print(a.attribute)

Output:

7

The design you explain is fine; the one issue it has is "I would like to extend the functionality by allowing this callback to use variables declared inside my_method".

While you can access variables defined inside my_method, from a design standpoint variables that you want to save in a meaningful manner are better as attributes in the instance. You will be able to modify them and they "save" automatically, while if you want to keep the results of things you define in my_method you will have to find another place to put them when the function call ends.

like image 118
Primusa Avatar answered Sep 29 '22 06:09

Primusa