Python Forum

Full Version: What is wrong with the code?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
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() 
(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. 

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

Thanks. I think I can also refer to target by using A.target.
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 456
change class variable
>>> Klass.Kvar = 999
>>> print(obj1.Kvar, obj1.var)
999 456
>>> print(obj2.Kvar, obj2.var)
999 456
change instance variable
>>> obj1.var = 888
>>> print(obj1.Kvar, obj1.var)
999 888
>>> print(obj2.Kvar, obj2.var)
999 456
As you can see there is one class variable, all object share that, where each object has its own instance variable.