hhh
hhh

Reputation: 52810

Why is `global var` needed in a class variable for class method to access it?

class Test:
    num1 = 1

# CASE 1
# WHY GLOBAL HERE? But no global below in CASE 2
    global num2
    num2 = 2

    def printNum2(self):
        return num2

## FAILURE WITH NON-GLOBAL num2, why?
# should print 2, with instance
i = Test()
print i.printNum2()



# CASE 2
#
#AUTOMATICALLY GLOBAL SCOPE?
num1=1

def print1():
    return num1


print print1()

Upvotes: 1

Views: 334

Answers (5)

unholysampler
unholysampler

Reputation: 17321

You don't need global to make printNum2 work correctly. Instead, use this:

class Test:
  num1 = 1
  num2 = 2

  def printNum2(self):
      return self.num2

You only need global if you want to do the following:

x = Test()
print num2
//instead of 
print x.num2

Upvotes: 4

ChrisJ
ChrisJ

Reputation: 5241

You should use self (e.g. self.num2) to reference a class variable or an instance variable from a method. global does not create a clarr or instance variable.

Upvotes: 0

Andrey Sboev
Andrey Sboev

Reputation: 7672

without "GLOBAL" num2 is a member of class so you should write self.num2

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798446

class creates a new scope. Since you use global, you force the name into the module scope instead of the class scope.

In other words, you have not created a class variable; you have simply created another global variable.

Upvotes: 2

Xavier Combelle
Xavier Combelle

Reputation: 11195

Because when you affect a variable python automatically suppose that it is a local variable

Upvotes: 1

Related Questions