Python: How to get Outer class variables from inner static class?

為{幸葍}努か 提交于 2019-12-11 20:39:03

问题


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**

回答1:


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




回答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


来源:https://stackoverflow.com/questions/10840270/python-how-to-get-outer-class-variables-from-inner-static-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!