0

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.

Flying Thunder
  • 890
  • 2
  • 11
  • 37

2 Answers2

1

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()
Matt Messersmith
  • 12,939
  • 6
  • 51
  • 52
  • Damn, i just came back to python and the difference between foo, foo() and f1=foo() always confused me. Thanks! Additional question: Are there cases where what i did ("annymous" asignment) are ever useful? – Flying Thunder Oct 04 '18 at 14:42
0

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()
NickNick
  • 223
  • 1
  • 10