Simple question that i cant figure out: I have (example) file one with this:
class foo:
var = 1
def bar(self):
print(self.var)
if __name__ == "__main__":
foo().bar()
and file2 with this:
from testing import foo
class foo2:
def bar2(self):
foo().var = 2
foo().bar()
foo2().bar2()
It returns 1, so no overwriting happening here.
I cant figure out how to actually overwrite the variable of the imported class instance. I checked this and this but that didnt help me. Sorry for asking such a simple question, thanks in advance.
2 Answers 2
It is being overwritten, but you're discarding the object immediately. foo().var = 2 creates an anonymous foo object, and assigns it's var to 2. The problem is you're not keeping a reference to the foo object you've just created. Then, foo().bar() creates a new foo object, which has var == 1 (just like all new foo objects since that's what your class does) and also calls the bar() member function on this new foo object, which will print 1 to console.
Try this instead:
def bar2(self):
foo_obj = foo()
foo_obj.var = 2
foo_obj.bar()
1 Comment
When you're doing foo().bar() , you're creating a second instance.
Try this:
test = foo() test.var = 2 test.bar() # foo().var = 2 # foo().bar()
foois a class,foo()is an instance. You seems to mix those notions.