从父级访问另一个子类

时间:2015-07-03 10:18:14

标签: python python-2.7

我有代码:

class Class1(object):
    class Class2:
        var1 = value1

    class Class3:
        var1 = Class2.var1 + value2

如何在Class3中访问Class2中我想要的值?

2 个答案:

答案 0 :(得分:2)

您可以使用@classmethod来访问class变量,而无需实例化类

In [17]: class Class1(object):
    class Class2:
        @classmethod
        def setvar(cls,value):
            cls.var1 = value
    class Class3:
        @classmethod
        def setvar(cls, value):
            cls.var1= value
    @classmethod
    def c2var(cls, val):
        cls.Class2.setvar(val)
    @classmethod
    def c3var(cls, val):
        cls.Class3.setvar(val + cls.Class2.var)


In [18]: Class1.c2var(5)

In [19]: Class1.c3var(9)

In [20]: Class1.Class2.var1
Out[20]: 5

In [21]: Class1.Class3.var1
Out[21]: 14

答案 1 :(得分:1)

您可以通过定义@classproperty

来延迟计算
class classproperty(object):
    def __init__(self, f):
        self.f = f
    def __get__(self, obj, owner):
        return self.f(owner)

现在你只需要这个:

class Class1(object):
    class Class2:
        var1 = 1
    class Class3:
        @classproperty
        def var1(cls):
            return Class1.Class2.var1 + 1

一些输出:

>>> Class1.Class3.var1
2
>>> Class1.Class2.var1 = 3
>>> Class1.Class3.var1
4