code kid
code kid

Reputation: 414

Return False if initialization of a class object has undesired values in Python

I need to return False if an Object instantiation does not have the appropriate values. As far as I know this is not possible to do this with an init method. Is there another method that I can use to check the values are return a bool value?

class Test:
    def __init__(self,x,y,z):
        if x == 0 and y == 0 and z == 0:
            return False
        self.x = x
        self.y = y
        self.z = z

print(Test(0, 0, 0)) #should return False

Upvotes: 2

Views: 2245

Answers (1)

tep
tep

Reputation: 833

Test(0,0,0) is an invocation of a constructor and will always return an instance of the Test class. Trying to return any value from __init__ will result in a TypeError.

What you really want here is a Factory Pattern. TestFactory provides a static method for creating tests which will return None, a more reasonable value for "invalid" objects, in your special case and otherwise just a plain test.

class Test:
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z

class TestFactory:
    @staticmethod
    def create_test(x,y,z):
        if x == 0 and y == 0 and z == 0:
            return None
        else:
            return Test(x,y,z)

print(TestFactory.create_test(0,0,0))

Upvotes: 2

Related Questions