CrazyC
CrazyC

Reputation: 1896

python:class member variable null or undefined

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. 

Upvotes: 0

Views: 1479

Answers (3)

CrazyC
CrazyC

Reputation: 1896

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)

Upvotes: 0

n_estrada
n_estrada

Reputation: 86

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

Upvotes: 0

chepner
chepner

Reputation: 532053

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")

Upvotes: 1

Related Questions