1

I've got class A and its inner class B

They're in different files(suppose a.py and b.py)

I need to change A.x in method of class B without sending "self". I.e. self.inner = B() and not self.inner = B(self). I can't send "self" because class A is in generated file that I mustn't touch.

How do I do it?

That's how I'd do it if I could send self

#a.py
from b import B
class A():
    def __init__(self):
        self.x = 1
        #this would be self.inner = B() instead
        self.inner = B(self)

example = A()
print(example.x)


#b.py
class B():
    def __init__(self, parent):
        self.change(parent)

    def change(self, parent):
        parent.x = 2
  • `B()` is initialized as an instance attribute or class attribute of `A`? If the latter, can possibly use the `__get__` descriptor to achieve your purpose. See https://stackoverflow.com/questions/3798835/understanding-get-and-set-and-python-descriptors – r.ook Jan 28 '19 at 16:39

2 Answers2

1

You could try that with the inspect module (although as @Slam advises, it's far from being recommended):

import inspect
class B():
    def __init__(self):
        inspect.currentframe().f_back.f_locals["self"].x = 2

class A():

    def __init__(self):    
        self.x = 1
        self.inner = B()
    def print_x(self):
        print(self.x)

a = A()
a.print_x()
Adonis
  • 4,670
  • 3
  • 37
  • 57
0

I believe you can so dome black magic with inspect module.

But I advise you re-thinking if you really need this, and why. Because this is good example of breaking the ideas of OOP and sane architecture overall — outer scopes should not be altered until they're explicitly providing you a handle to do so. In case you're not following this idea, you'll get super-tightly coupled code.

Slam
  • 8,112
  • 1
  • 36
  • 44
  • I'm using PyQt5 and QtDesigner(with pyuic generated file), so I don't know how to implement it the other way. I need to change App.canvas in its inner Slider Class. App inherits Ui_MainWindow, which sets Slider Class as its attribute(I can't really change Ui_MainWindow class, this one is generated). It goes like self.y = QWidget(...), self.x = Slider(self.y) in generated file. – Brainless Duck Jan 28 '19 at 16:35