self, local, global, and arg's

It seems my understanding of all these concepts have been corrupted in my previous programming use- and it also seems my progress in learning in the past six months has slid backwards or also corrupted.

99% of all my problems go back to being able to properly pass information about objects within various functions. Everytime I think I get it understood I miscall a variable before assigment error.

I bought a python book but it just shows code example and I don’t see Why I am suppossed to do what. So here is my question.

As I understand it :

Self = this particular item true?

Global = a variable that can be accessed by any function- (I have a problem with this as I somehow always end up with a function calling my global variable as local) true?

local = variables created in a specific function or class, or block of code True?

Therefore if I have a global variable

global health, monsterheath

how do I reference that in a function:

def attack()
    health += -1

I know this seems so basic- that it is embarrassing, but it just keeps popping back up.

JB SKaggs

Yes, ‘self’ is the same as ‘this’ in java meaning this specific instance.
I think global is right, too (im not using it because of just that).
The local-thing is more complicated:
Warning: variables are NOT just defined for a block.
every variable can be used from the level where it was initializied normally,
when using it in functions or classes you can still access it but reassigning a new object (=) to the variable doesnt affect the lower levels (Warning: you can still change the properties of the object).
levels meaning ‘class’ and ‘def’ and all combinations :wink:
variables defined inside a class can either be referenced using the class or any instance (all sharing the same variable - roughly equivalent to ‘static’ in java)

for your global example id rather do:

class health(object):
   player=100
   monster=209654

def attack()
    health.player -= 1

but as you propably see this isnt very elegant…
guessing what you want maybe this fits better:

class Attackable:
   def __init__(self,health):
      self.health=health
   def attack(self):
      self.health-=1

player=Attackable(100)
monster=Attackable(100)

I personally think Byte of Python could be a good (re-)start as there are some references to other languages

Thank you that was quik and helpful.

JB

In answer to your original question: The keyword global in Python makes the interpreter look for the named variable in the next level outside of whatever function/code block you are working in. Ex:


health = 10

def attack():
      global health #<== health in this block is now the same as the exterior block
      health -= 1

In python you don’t declare variables global, but rather you inform the interpreter to look at a wider area. I don’t personally like the global statement and avoid it whenever possible; as the previous poster mentioned working with classes makes it much easier.

So i guess if you wont use classes youll have to do:
x = 1
y = 2
def func():
global x
global y
def func2():
global x
global y
?
Thats ‘importing’ your variable in every function.
I wonder why you cant write:
global x = 1
def func():
print x
def func2():
print x
And use x in any function…

This just works:

x = 1
def func():
   print x
def func2():
   print x 

:wink:

facepalm
How about this one?:
x = 1
def func():
x = x + 2
print x
?

seriously: if you could define a variable global then youd have to make sure none of the libraries you use uses that name internally - i personally wouldnt want to do that.

you have to make x global in that case, but I wouldn’t recommend it :wink:

Instead try:

class myClass():
     def __init__(self):
          self.x=1

     def func(self):
          self.x+=2
    
     def printX(self):
          print self.x

main():
     exampleClass=myClass()
     exampleClass.printX()

This is how self works, and the gist of oop as I get it. If you want different functions to use the same variables, put a self. in front of it. If you have a self contained function with variables that other functions won’t need, don’t put the self.

if you have something like what’s below, all the x will be different, and can only be used inside each function.

class ofXes():
     def func1():
          x=5
     def func2():
          x=3
     def func3():
          x=4

print x #ERROR! X DOESN'T EXIST

Thats what i do.
Ima fool who doesnt like classes

you could use dictionaries or lists instead - same effect

I felt the same at some point.
you will still have to learn them. it’s MUCH easier and productive once you master them.

Yeah, I’ve found that having lots of global variables in your app gets messy really quickly.

I don’t usally, usally I do only when I get lazy and don’t fulll want to name the variables right (or what I call “right”).

art global vars only global on module level, globals vars aren’t really shared between modules. The true globals are the

 __builtint__.superGlobalVar = World() 

…and that’s really yucky, exactly why I dislike DirectStart so much.

Some notes about global vars :

  1. on read, you don’t need to declare it global, because if that var doesn’t exist locally, python will look globally
  2. on write, you must declare it global, otherwise it will end up as local var

If you’re too lazy to use class, or even tired declaring “global x” every time in your functions, you could try this :

G = sys.modules[name]

Then you could read/write your vars from G :
G.x=123
print x

I get it now. Thanks

What about classes though?

When I switched to using classes during this topic post- I notice that my game produces an original object of the class- then it makes copies.

class backgroundmusic(object):#load background music and play
    music = base.loadMusic('sounds/The_Amulet.mp3')
    music.setVolume(1)   #Volume is a percentage from 0 to 1
    music.setLoopCount(0) #0 means loop forever, 1 (default) means
    music.play()

the game loads the music irregardless of whether I call it with a

m=backgroundmusix()

or not.

How do I use classes but not create an object till I call it? For example maybe I may not want a particaulr object created until an event occurs.