I have two files (Backupfile.py and Backupfile2.py).
Following is in Backupfile.py:
class Mater:
def __init__(self):
self.func()
def func(self):
from Backupfile2 import klasse
newclass = klasse()
obj =[]
obj.append((1,1))
print(obj)
mater = Mater()
Now I want to import the class klasse
from Backupfile2.py to Backupfile.py and add (2,2) to the list obj
.
Following is in Backupfile2.py:
class klasse:
def __init__(self):
obj.append((2,2))
print(obj)
However, why doesn't the class klasse
know about the variable obj
once it is imported?
The class klasse doesn't know about the variable obj because it is not in the same scope. Variables from the local scopes are not shared with variables from a class. One easy solution is to use the global keyword but I wouldn't use it. I would consider passing the obj reference in the method args, like this:
class Mater:
def __init__(self, obj):
self.obj = obj
self.func()
def func(self):
from Backupfile2 import klasse
newclass = klasse(self.obj)
obj =[]
obj.append((1,1))
print(obj)
mater = Mater(obj)
class klasse:
def __init__(self, obj):
obj.append((2,2))
print(obj)
Apart from this specific question, I would advise you to take a beginner's course on Python.
I'm not sure about the answer because i'm not an expert and because i don't understand what do you want to do, but i think you miss the declaration of obj in the class "klasse", i think it should be something like
class klasse:
def __init__(self):
self.obj = []
self.obj.append((2,2))
print(obj)
or if you want to use the obj declaration that you did out, your code should be something like
class Mater:
def __init__(self, obj):
self.func(obj)
def func(self, obj):
from Backupfile2 import klasse
newclass = klasse(obj)
obj =[]
obj.append((1,1))
print(obj)
mater = Mater(obj)
and then your class "klasse" should be
class klasse:
def __init__(self, obj):
obj.append((2,2))
print(obj)
I hope it will help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.