0

I want to specify variable once by making instance Outer(variable), than this variable use in all static classes, how should I do that? Is there any other solution than use not static methods and pass Outer into each inner class?

class Outer():
    def __init__(self, variable):
        self.variable= variable

    class Inner1():        
        @staticmethod
        def work1():
            **print Outer.variable**

    class Inner2():        
        @staticmethod
        def work2():
            **print Outer.variable**
Meloun
  • 13,601
  • 17
  • 64
  • 93
  • 1
    Why the heck would you want inner classes or hand-made static classes in Python? There's no advantage. Python is not Java (and not C# either). Also, you seem to conflate instance variables (`some_obj.attr`) with class ("static") variables (`SomeClass.attr`). –  May 31 '12 at 19:50
  • 2
    [Guido van Rossum on static methods:](http://groups.google.com/group/python-ideas/browse_thread/thread/6d82fd23609eff9c/eabf958d7d5f8382?lnk=gst&q=staticmethod+Guido+van+Rossum#eabf958d7d5f8382) "They're basically an accident -- back in the Python 2.2 days when I was inventing new-style classes and descriptors, I meant to implement class methods but at first I didn't understand them and accidentally implemented static methods first. Then it was too late to remove them and only provide class methods." – Sven Marnach May 31 '12 at 19:51
  • There is an answer to a very similar question [here](http://stackoverflow.com/questions/6665196/how-can-i-acess-a-metod-from-an-object-inside-a-class-in-python-2-6/6665452#6665452) – brandizzi May 31 '12 at 20:01
  • for example in pyqt is using of static methods very often, http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qfiledialog.html - getSaveFileName(), etc. – Meloun May 31 '12 at 20:03
  • @Meloun That's because it's a binding to the C++ API which defines Qt. But in Python, there are few reasons for them, and module-level functions are far more idiomatic for most uses. Also, as another comment notes, `classmethod` is simply better. –  May 31 '12 at 20:23

2 Answers2

2

If you really want such thing, metaclass may help a little, for example:

from types import ClassType

class OuterMeta(type):
    def __new__(mcls, name, base, attr):
        ret = type.__new__(mcls, name, base, attr)
        for k, v in attr.iteritems():
            if isinstance(v, (ClassType, type)):
                v.Outer = ret
        return ret

class Outer(object):
    __metaclass__ = OuterMeta
    var = 'abc'    
    class Inner:
        def work(self):
            print self.Outer.var
        @classmethod
        def work2(cls):
            print cls.Outer.var

then

>>> Outer.Inner.work2()
abc
jayven
  • 770
  • 8
  • 19
1

No. Inner-class methods have no way of accessing instances of the outer class.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358