Brainless Duck
Brainless Duck

Reputation: 27

How to change outer class from inner class without sending self?

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

Upvotes: 1

Views: 67

Answers (2)

Adonis
Adonis

Reputation: 4818

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

Upvotes: 1

Slam
Slam

Reputation: 8572

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.

Upvotes: 0

Related Questions