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. 
CrazyC
  • 1,840
  • 6
  • 39
  • 60
  • Does this answer your question? [How do I check if a variable exists?](https://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists) – G. Anderson Apr 23 '20 at 16:50

3 Answers3

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")
chepner
  • 497,756
  • 71
  • 530
  • 681
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

chepner
  • 497,756
  • 71
  • 530
  • 681
n_estrada
  • 86
  • 7
  • 1
    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) ``` – CrazyC Apr 23 '20 at 16:54
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)
CrazyC
  • 1,840
  • 6
  • 39
  • 60