What is wrong with the code? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: What is wrong with the code? (/thread-1090.html) |
What is wrong with the code? - dullboy - Dec-02-2016 Here is the code, class A(): target = open("test.log", "a") def test(self): print "test" target.write("test\n") target.close() def main(): a = A() a.test() if __name__ == "__main__": main()There is an error: NameError: global name 'target' is not defined. Why? Thanks. RE: What is wrong with the code? - metulburr - Dec-02-2016 you are creating target as a class variable, when you meant to create it as an instance variable. class A(object): def __init__(self): self.target = open("test.log", "a") def test(self): print("test") self.target.write("test\n") self.target.close() def main(): a = A() a.test() if __name__ == "__main__": main() RE: What is wrong with the code? - dullboy - Dec-02-2016 (Dec-02-2016, 06:59 PM)metulburr Wrote: you are creating target as a class variable, when you meant to create it as an instance variable. Thanks. I think I can also refer to target by using A.target. RE: What is wrong with the code? - metulburr - Dec-02-2016 its not about how you refer to them...They are two completely different things. Ones a class variable and one is an instance variable. class Klass: Kvar = 123 def __init__(self): self.var = 456 obj1 = Klass() obj2 = Klass()Initial values of both >>> print(obj1.Kvar, obj1.var) 123 456 >>> print(obj2.Kvar, obj2.var) 123 456change class variable >>> Klass.Kvar = 999 >>> print(obj1.Kvar, obj1.var) 999 456 >>> print(obj2.Kvar, obj2.var) 999 456change instance variable >>> obj1.var = 888 >>> print(obj1.Kvar, obj1.var) 999 888 >>> print(obj2.Kvar, obj2.var) 999 456As you can see there is one class variable, all object share that, where each object has its own instance variable. |