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)
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"
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)
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"