Python check __init__

I have been trying to figure this out for the past few hours, and I'm going to refuse.

How do you make sure that in python only specific relevant criteria will be created by the object?

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

Let's say

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

Thank.

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

constructor parameter check

How to overload __init__ method based on argument type?

+5
source share
2 answers

You must define __new__for this:

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

, __init__ :

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

:

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

All Articles