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.

3
  • 1
    foo is a class, foo() is an instance. You seems to mix those notions. Commented Oct 4, 2018 at 14:32
  • Possible duplicate of python: class attributes and instance attributes Commented Oct 4, 2018 at 14:34
  • But i created an instance in file2 didnt i? What would the working code have changed? Commented Oct 4, 2018 at 14:38

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

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?
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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.