0

Say I have the following script:

file.py:

class A():
  def a(self):
    var={'a':1,'b':2...}

Can I access var externally (something like: import file; file.A.a.var['a'])?

Thanks!

martineau
  • 119,623
  • 25
  • 170
  • 301
Hailiang Zhang
  • 17,604
  • 23
  • 71
  • 117

2 Answers2

3

No, you can't access it. That dictionary is only created when the method is called.

If you can modify the source code you can:

  • move the construction of the dictionary to the class constructor or to the module level
  • or return a reference to the dictionary from the method
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

you can't access a variable because it's created when class A is initialized so you can access it with the instance of A (with self reference, but you'll have to update 3rd line to self.var), or you can declare it static (if it should be shared by all instances of A, then you can create it as a static variable more on static variables here

Community
  • 1
  • 1
Jan Vorcak
  • 19,261
  • 14
  • 54
  • 90