chemelnucfin
chemelnucfin

Reputation: 411

Python checking __init__ parameter

I've been trying to figuring this out for the last few hours, and I'm about to give up.

How do you make sure that in python only a matching specific criteria will create the object?

For example, let's say I want to create an object Hand, and initialize a Hand only when I have enough Fingers in the initializer? (Please just take this as an analogy)

Say,

class Hand:
  def __init__(self, fingers):
    # make sure len(fingers)==5, and 
    #only thumb, index, middle, ring, pinky are allowed in fingers
    pass

Thanks.

These are the closest questions I found, but one is in C++, the other does not answer my question.

checking of constructor parameter

How to overload __init__ method based on argument type?

Upvotes: 7

Views: 11842

Answers (2)

georg
georg

Reputation: 214969

You have to define __new__ for that:

class Foo(object):
    def __new__(cls, arg):
        if arg > 10: #error!
            return None 
        return super(Foo, cls).__new__(cls)

print Foo(1)    # <__main__.Foo object at 0x10c903410>
print Foo(100)  # None

That said, using __init__ and raising an exception on invalid args is generally much better:

class Foo(object):
    def __init__(self, arg):
        if arg > 10: #error!
            raise ValueError("invalid argument!") 
        # do stuff

Upvotes: 6

AI Generated Response
AI Generated Response

Reputation: 8845

Try asserting:

class Hand(object):
    def __init__(self,fingers):
        assert len(fingers) == 5
        for fing in ("thumb","index","middle","ring","pinky"):
            assert fingers.has_key(fing)

Upvotes: 0

Related Questions