Search code examples
pythonclassoopclass-attributes

Access class level attribute of another class?


I can access class-level attribute of a class (B) in method of another class (A) but I cannot access that at class-level of class A. The issue can be resolved by defining B after A but why is this so and how can I access that keeping class B after class A.

I am looking for solution without class inheritance and without creating object of class B inside __init__ of class A.

See the code here:

class A:
    a=B.b # This doesn't work
    def __init__(self):
        print(B.b) #This works
class B:
    b=[1,2,3]

Solution

  • Assuming you don’t need to use the attribute while defining A (e.g., for a default argument), you can just assign it later:

    class A:
        def __init__(self):
            print(B.b)
    class B:
        b=[1,2,3]
    A.a=B.b
    

    or even

    class A:
        def __init__(self):
            print(B.b)
    class B:
        A.a=b=[1,2,3]
    

    if you consider the classes so closely related that an assignment to one inside the other is less surprising than one outside both.