开发者

Python - cant access a variable within the class

开发者 https://www.devze.com 2023-03-07 11:34 出处:网络
I have a basic python question. I\'m working on a class foo and I use __init__(): to do some actions on a value:

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:
     开发者_JS百科  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


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


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


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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消