Python Forum

Full Version: NameError with global
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
(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?
the drawing variable is still titlescreen class ,right?
  
At the same time,can anyone teach me how to use the keyword self?

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