NameError with global - 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: NameError with global (/thread-2086.html) |
NameError with global - hsunteik - Feb-18-2017 class titlescreen: global drawing drawing ='...drawing...' def drawbackground(filename,constant=True): if constant==True: print ('===non-animated title screen===') print(drawing) elif constant==False: print('===animated title screen===') print (drawing) else: print('===unknown background type===') print('===cannot draw background===') titlescreen.drawbackground('yuzsgxsw')i need to make the variable drawing global before using it,if not it will give NameError,why? the drawing variable is still titlescreen class ,right? At the same time,can anyone teach me how to use the keyword self? RE: NameError with global - Ofnuts - Feb-18-2017 (Feb-18-2017, 03:34 AM)hsunteik Wrote:class titlescreen: global drawing drawing ='...drawing...' def drawbackground(filename,constant=True): if constant==True: print ('===non-animated title screen===') print(drawing) elif constant==False: print('===animated title screen===') print (drawing) else: print('===unknown background type===') print('===cannot draw background===') titlescreen.drawbackground('yuzsgxsw')i need to make the variable drawing global before using it,if not it will give NameError,why? You are not using classes properly: class TitleScreen: # using CamelCase for classes is a good habit # This defines a class variable # Attributes are defined by being set in the constructor # (the __init__(self,...) function drawing ='...drawing...' # Note the "self" argument in method arguments. # "self" is the instance on which the methods are called. # It is automatically added and set by the method call mechanism in Python # Inside the method you use "self" to reference class variables # or instance variables (these latter are better called "attributes") def drawbackground(self,filename,constant=True): if constant==True: print ('===non-animated title screen===') print(self.drawing) elif constant==False: print('===animated title screen===') print (self.drawing) else: print('===unknown background type===') print('===cannot draw background===') ts=TitleScreen() # Create class instance ts.drawbackground('yuzsgxsw') # "self" will be add befire first paramater ts.drawbackground('yuzsgxsw',False) # "self" will be add befire first paramater RE: NameError with global - ichabod801 - Feb-18-2017 A tutorial on class basics. |