0

I am new in python and creating a class which have few variables but in my process method in want check whether few member variables are being set or not. Just like java script undefined or if i can set null. I don't want to use any default values: how i can check null or undefined?

class MyClass:
  def __init__(self, name, city):
      self.name = name
      self.city = city

  def setState(self,state)
      self.state = state

  def process(self):
      print("Name:", name)
    # here i want check whether state is being  set or not. 
    # How can i do it. I tried  if self.state is None but getting 
    # exception AttributeError. 
1

3 Answers 3

1

You can use hasattr

if hasattr(self, 'state'):
    ...

or catch the AttributeError yourself (which, really, is all that hasattr does):

try:
    x = self.state
except AttributeError:
    print("No state")
else:
    print(f"State is {x}")

However, it's far better to simply initialize the attribute to None in the __init__ method.

def __init__(self, name, city):
    self.name = name
    self.city = city
    self.state = None

Then you can simply check the value of self.state as necessary.

if self.state is not None:
    ...

As an aside, unless you want to perform some sort of validation on the value of state, just let the user access self.state directly rather than using a method to set the value.

x = MyClass("bob", "Townsville")
x.state = "Vermont"  # rather than x.setState("Vermont")
Sign up to request clarification or add additional context in comments.

Comments

0

You can check if variables are being set by using

def process(self):
    print('Name:',name)
    if self.state is not None :
        print('State:': self.state)

is None is python's way of checking if something was set or not

1 Comment

Thanks it worked but needed one more steps. I set state = None in constructor and then ``` if self.state is not None : print('State:': self.state) ```
0

Thanks it worked but needed one more steps. I set state = None in constructor and then

class MyClass:
  def __init__(self, name, city):
      self.name = name
      self.city = city
      self.state = None

def process(self):
    print('Name:',name)
    if self.state is not None :
        print('State:': self.state)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.