0
class A(object):
    class B(object):
        def __getitem__(self, key):
            # Obviously not the same self here...
            x = self.function_A_needs_as_well(key)  

    def function_A_needs_as_well(self, value):
        pass

I hope the example is not too bad and at least somewhat self-explaining. Can someone tell me how to call "function_A_needs_as_well" from inside "class B"?

Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
  • 2
    Why do you think you need nested classes? – Markus Meskanen Jun 22 '15 at 12:51
  • I have a [similar question once](http://stackoverflow.com/questions/8878344/defining-a-class-within-another-class-and-calling-a-parent-method) – Mp0int Jun 22 '15 at 13:09
  • For the most part I was trying to subclass a string (type), that is just used inside class A. When a nested class is not possible without ugly code, I stay with the solution I already had. Thanks, guys! –  Jun 22 '15 at 13:17

3 Answers3

7

Python is not Java. Nested classes get no special access to their containing classes. Because of this, there is almost no reason to nest them at all.

If an instance of B needs access to an instance of A, you need to pass it in somewhere.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

I'm not certain I fully understand your question but could you not simply get class B to inherit class A and then call the class A function, passing in a value at the function call?

class A(object):

    def __init__(self, name="Object A"):
        self.name = name

    def classAfunction(self, value):
        print("This value has been passed to me: ", value)



class B(A):

    def __init__(self, name="Object B"):
        self.name = name
        super().__init__(name = "Object A")



ObjectB = B()

ObjectB.classAfunction("Banana")

input()
sw123456
  • 3,339
  • 1
  • 24
  • 42
0

There is no implicit way to access outer class from inner class but you can explicitly pass a reference of the outer class while constructing inner class. Have a look at the following code. I don't know your design concerns have a look at the following stackoverflow post

class A(object):
    class B(object):
        def __init__(self, a_instance=None):
            self.a_instance = a_instance
        def __getitem__(self, key):
            # Obviously not the same self here...
            if self.a_instance is not None:
                x = self.a_instance.function_A_needs_as_well(key)

    def test_from_inside_A(self):
        b = A.B(self)
        b.__getitem__(2)

    def function_A_needs_as_well(self, value):
        pass

##test from outside A
a = A()
b = A.B(a)
b.__getitem__(2)
Community
  • 1
  • 1
Kavin Eswaramoorthy
  • 1,595
  • 11
  • 19