Jose187
Jose187

Reputation: 449

Global name inside a class is not defined

So I've been messing around with this all day, and I still can't get it to work

class pleaseWork:
    def __init__(self):
        self.foo=printThis(1)
        self.bar=printThis(2)
    def printThis(x):
        if x==1:
            print "foot"
        elif x==2:
            print "bar"

result=pleaseWork()

result.bar

It just returns

NameError: global name 'printThis' is not defined

please tell me why it's not working...

Upvotes: 0

Views: 3175

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

Because printThis is an attribute of the current object.

self.foo = self.printThis(1)

Upvotes: 5

Ionut Hulub
Ionut Hulub

Reputation: 6326

class pleaseWork:
    def __init__(self):
        self.foo=self.printThis(1)
        self.bar=self.printThis(2)
    def printThis(self, x):
        if x==1:
            print "foot"
        elif x==2:
            print "bar"

result=pleaseWork()

result.bar

Upvotes: 1

Related Questions