0

I have the code:

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

    class Class3:
        var1 = Class2.var1 + value2

How can I access in Class3 the value I want from Class2?

berendeanicolae
  • 100
  • 1
  • 8

2 Answers2

2

You can use @classmethod's to access class variables without instantiating the 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
shaktimaan
  • 1,769
  • 13
  • 14
  • I would like to have values instead of methods because I am using reflection to build an object from the values from that class (and I would like to initialize the values inside the class). – berendeanicolae Jul 03 '15 at 10:34
  • That can not be done coz there is no way for python to confirm whether parent class has the attribute you want from it until class itself is defined. – shaktimaan Jul 03 '15 at 10:44
  • I that case, I think I can come up with some modifications to use your solution. Thanks! – berendeanicolae Jul 03 '15 at 10:49
  • @shaktimaan: you don't need anything to access *class* attributes without instanciating the class - a class is an object too (instance of it's metaclass), and as such works just like any other object. – bruno desthuilliers Jul 03 '15 at 12:05
  • 1
    @ bruno desthuilliers I didi not mean that the class needs to be instantiated before accessing its attributes. I meant that it needs to be defined atleast. In the case above you wont be able to access `Class1` inside `Class3` (as requested by user) as the `Class1` is itself in process of defining. – shaktimaan Jul 03 '15 at 12:16
1

You can delay the computation by defining @classproperty:

class classproperty(object):
    def __init__(self, f):
        self.f = f
    def __get__(self, obj, owner):
        return self.f(owner)

Now all you need is this:

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

Some output:

>>> Class1.Class3.var1
2
>>> Class1.Class2.var1 = 3
>>> Class1.Class3.var1
4
Community
  • 1
  • 1
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88