Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 975
chemelnucfin Avatar asked Jun 02 '12 23:06

chemelnucfin


People also ask

What is the __ init __ in Python?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

Can you call __ init __ again?

3 Answers. Show activity on this post. It's fine to call __init__ more than once on an object, as long as __init__ is coded with the effect you want to obtain (whatever that may be). A typical case where it happens (so you'd better code __init__ appropriately!-)

How do you initialize attributes in Python?

Use the __init__() method to initialize the object's attributes. The __init__() doesn't create an object but is automatically called after the object is created.

Can __ init __ return value Python?

__init__ method returns a value The __init__ method of a class is used to initialize new objects, not create them. As such, it should not return any value. Returning None is correct in the sense that no runtime error will occur, but it suggests that the returned value is meaningful, which it is not.


1 Answers

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
like image 198
georg Avatar answered Oct 18 '22 12:10

georg