Martin
Martin

Reputation: 143

Python - cant access a variable within the class

I have a basic python question. I'm working on a class foo and I use __init__(): to do some actions on a value:

class foo():
  def __init__(self,bar=None):
    self.bar=bar
    if bar is None: 
       isSet=False  
    else:
       isSet=True
  print isSet

When I execute the code I get: NameError: name 'isSet' is not defined.
How can I access isSet? What am I doing wrong?

regards, martin

Upvotes: 1

Views: 252

Answers (5)

martineau
martineau

Reputation: 123531

In your code, isSet is a class attribute, as opposed to an instance attribute. Therefore in the class body you need to define it before referencing it in the print statement. Outside the class and in its methods, you must prefix it with the class name and a dot, i.e. Foo. in this case. Note that the code in def __init__() function body does not execute until you create an instance of the Foo class by calling it.

class Foo(object):
    isSet = None

    def __init__(self, bar=None):
        self.bar = bar

        if bar is None:
           Foo.isSet = False
        else:
           Foo.isSet = True

    print isSet

f = Foo()
print Foo.isSet

output:

None
False

Upvotes: 1

Evpok
Evpok

Reputation: 4485

I'd try

class foo():
  def __init__(self,bar=None):
    self.bar = bar
    self.is_set = (bar is None)

Then inside the class

...
def spam(self, eggs, ham):
    if self.is_set:
        print("Camelot!")
    else:
...

Have you read the doc's tutorial's entry about classes?

Upvotes: 1

phihag
phihag

Reputation: 288290

The indentation of the final line makes it execute in the context of the class and not __init__. Indent it one more time to make your program work.

Upvotes: 0

Björn Pollex
Björn Pollex

Reputation: 76886

It depends on what you are trying to do. You probably want isSet to be a member of foo:

class foo():
  def __init__(self,bar=None):
    self.bar=bar
    self.isSet=True
    if bar is None: 
       self.isSet=False  

f = foo()
print f.isSet

Upvotes: 3

Cat Plus Plus
Cat Plus Plus

Reputation: 130004

Wrong indentation, it should be this instead, otherwise you're exiting the function.

class foo():
  def __init__(self,bar=None):
    self.bar=bar

    if bar is None: 
       isSet=False  
    else:
       isSet=True

    print isSet

Upvotes: 4

Related Questions