tags:

views:

47

answers:

2

I have a python class/object as follows.

class Hello:
    def __init__(self):
        self.x = None
        self.y = None
        self.z = None


h = Hello()
h.x = 10
h.y = 20
# h.z is not set

I need to check if all the member variables are set (not None). How can I do that automatically?

for value in ??memeber variables in h??:
    if value == None:
        print 'value is not set'
+3  A: 
class Hello(object):
    def __init__(self):
        self.x = None
        self.y = None
        self.z = None
    def is_all_set(self):
        return all(getattr(self, attr) is not None for attr in self.__dict__)

though, as @delnan said, you should prefer to make it impossible for the class to always be in a valid state (this is referred to as preserving "class invariants")

Lie Ryan
A: 

I need to check if all the member variables are set (not None).

Why?

You need the member variables in order to do some processing in the class.

class Hello:
    def __init__(self):
        self.x = None
        self.y = None
        self.z = None
    def some_processing( self ):
        assert all( self.x is not None, self.y is not None, self.z is not None )
        # Now do the processing.
S.Lott