I have a situation like so...
class Outer(object):
def some_method(self):
# do something
class Inner(object):
def __init__(self):
self.Outer.some_method() # <-- this is the line in question
How can I access the Outer
class's method from the Inner
class?
maybe I'm mad but this seems very easy indeed - the thing is to make your inner class inside a method of the outer class...
Plus... "self" is only used by convention, so you could do this:
It might be objected that you can't then create this inner class from outside the outer class... but this ain't true:
then, somewhere miles away:
even push the boat out a bit and extend this inner class (NB to get super() to work you have to change the class signature of mooble to "class mooble( object )"
later
mrh1997 raised an interesting point about the non-common inheritance of inner classes delivered using this technique. But it seems that the solution is pretty straightforward:
You're trying to access Outer's class instance, from inner class instance. So just use factory-method to build Inner instance and pass Outer instance to it.
Do you mean to use inheritance, rather than nesting classes like this? What you're doing doesn't make a heap of sense in Python.
You can access the
Outer
's some_method by just referencingOuter.some_method
within the inner class's methods, but it's not going to work as you expect it will. For example, if you try this:...you'll get a TypeError when initialising an
Inner
object, becauseOuter.some_method
expects to receive anOuter
instance as its first argument. (In the example above, you're basically trying to callsome_method
as a class method ofOuter
.)Expanding on @tsnorri's cogent thinking, that the outer method may be a static method:
Now the line in question should work by the time it is actually called.
The last line in the above code gives the Inner class a static method that's a clone of the Outer static method.
This takes advantage of two Python features, that functions are objects, and scope is textual.
...or current class in our case. So objects "local" to the definition of the Outer class (
Inner
andsome_static_method
) may be referred to directly within that definition.The methods of a nested class cannot directly access the instance attributes of the outer class.
Note that it is not necessarily the case that an instance of the outer class exists even when you have created an instance of the inner class.
In fact, it is often recommended against using nested classes, since the nesting does not imply any particular relationship between the inner and outer classes.
I found this.
Tweaked to suite your question:
I’m sure you can somehow write a decorator for this or something
related: What is the purpose of python's inner classes?