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**
5
  • 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). Commented May 31, 2012 at 19:50
  • 2
    Guido van Rossum on static methods: "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." Commented May 31, 2012 at 19:51
  • There is an answer to a very similar question here Commented May 31, 2012 at 20:01
  • for example in pyqt is using of static methods very often, riverbankcomputing.co.uk/static/Docs/PyQt4/html/… - getSaveFileName(), etc. Commented May 31, 2012 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. Commented May 31, 2012 at 20:23

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.