0

I'm trying to call for value from class B that is nested in class A and use it in class C. I'm getting AttributeError:

class A():
    class B():
        a = 1
    class C():
        b = 2
        c = B.a + b 
AttributeError: class B has no attribute 'a'

I also tried to call From 'A', Pycharm recognize it, but python still get AttributeError:

class A(object):
    class B(object):
        a = 1
    class C(object):
        b = 2
        c = A.B.a + b 
AttributeError: class A has no attribute 'B'

Does someone have an idea of how to use it? Thanks

0

3 Answers 3

1

The problem is that the class template (A) is not constructed while you're calling A.B.a. That is, A is not bound yet to a class.

Try this workaround:

class A():
    class B():
        a = 1

Now create C separately (A is already defined):

class C():
    b = 2
    c = A.B.a + b

And reference C from A:

A.C = C

This can possibly be done via meta-classes, but could be an over-kill here.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm trying to avoid creating a separate class, I'm trying to stick the formation of nested classes.
0

At compile time, the class definition for class A is not complete hence you can not access the classes, variables and methods defined in a parent class inside a nested class.

You can try separating the class definitions though as suggested by @Reut Sharabani.

Comments

0

You can not access the class by its name, while the class definition statement is still executed.

class A(object):
   class B(object):
       a = 1
   class C(object):
       b = 2
       c = A.B.a + b # here class A statement is still executed, there is no A class yet

To solve the problem you must defer the execution of those statements :

  • move the all those statements to a classmethod
  • call them after the classes was defined.

class A(object):
    class B(object):
        @classmethod
        def init(cls):
            cls.a = 1
    class C(object):
        @classmethod
        def init(cls):
            cls.b = 2
            cls.c = A.B.a + cls.b 

    @classmethod
    def init(cls):
        cls.B.init()
        cls.C.init()

A.init()

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.