Monday, December 24, 2012

Global value on Python

Nice to meet you!
This is my first article in my blog.
I study Robotics at University in Japan.
So I write mainly about robots and programs.

Summary:
This page is written about global value on Python.
You have to declare a 'global' to use global variables in Python.
I show some example ,and in last describe how to use global variables in class.

I show how to use simple global variables.
You can use a global variables by declaring a 'global' in the function
g1 = 0
def gl_test1():
    global g1
  print g1

gl_test1()

EXECUTION RESULT
0
Next I try to change the value of a global variables.
You can recognize that saved the value adding one to every call.
g2 = 0

def gl_test2():
    global g2
    g2 += 1
    print g2

for i in range(10):
    gl_test2()

EXECUTION RESULT
1
2
3
4
5
6
7
8
9
10
Last, I show example of using global variables at Class.
You can access a global variables from the class by putting 'self' as an example.
I recommend that you access to the global variables via the method.
class GlTest(object):
    g = 0
   
    def get(self):
        global g
        return self.g
        
  def add(self, x):
      global g
       self.g += x

gc = GlTest()
gc.get()

EXECUTION RESULT
0

gc.add(100)
gc.get()

EXECUTION RESULT
100
Thanks you for read my page.

1 comment:

  1. Golden Nugget Casino, Las Vegas - Mapyro
    Golden Nugget Casino offers over 3100 gaming machines including video poker, 하남 출장안마 blackjack, roulette, 경상북도 출장마사지 craps, keno, poker, 시흥 출장샵 bingo and 춘천 출장샵 more. 속초 출장마사지

    ReplyDelete