0
How to access caller class attribute
Hi I have a class which constructor calls another class and one more class is called from constructor. Basically, class A, B and C are there. A constructor holds B and B constructor holds C. From method of C, how to access attribute of A class? Refer code below. Basically, I need to access author attribute inside display method. https://sololearn.com/compiler-playground/cktuVcBRYRTn/?ref=app
7 Réponses
+ 4
can you modify the display method so that it can accept arguments? then obj can supply it with it's obj._author attribute as function argument.
test2 have no way of knowing about test unless it is instanced inside display or the obj._author is passed to the display function.
+ 2
It looks like @Bob_Li gave you some info in your comments. Is that what you're looking for?
+ 2
I create an instance of test (A) and call the display method on the instance of test2 (C), and pass the instance of test as caller. The display method then prints the author attribute of the test instance.
https://sololearn.com/compiler-playground/cPvgWKlPZ883/?ref=app
+ 2
Why not use inheritance?
just change your "def test:" to "def test(test1):"
same with test1, but not on test2 since it's your base class.
See here for modified code: https://www.sololearn.com/en/compiler-playground/cW3f4Wem8tLJ
I also left comments on what I have changed, and see the output :)
+ 1
I'm sorry, I'm not sure that I understand.
Can you give me an example of what you'd like to see?
You want to call the display method and what should then output?
0
Unfortunately no. I don't have access to change this design even though it is wrong as it is kind of legacy code .
I still need to access the author if it is possible by any means
0
Display method should output author from test class.