Python – How to access Instance variables?

Question:

I recently stumbled upon a problem, How do i access a class’s instance variables (aka the variables inside __init__) from outside/inside the file without creating an instance of a class (i.e main = main.foo()).

Example:

class foo:
       def __init__(self,name):
           self.name = name
class bar:
    os.mkdir(foo.name)
Asked By: retr0cube

||

Answers:

you can set the variable as global, and then you will be able to access this variable from everywhere. and also modifying it.

Not sure why you are using nested classes, but:

foo_name = None
class main:
    class foo:
       def __init__(self,name):
           global foo_name
           foo_name = self.name = name
    class bar:
       def __init__(self):
           print(foo_name)


main.foo("Jonathan")
main.bar()

Prints out "Jonathan"

Answered By: Jonathan1609
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.