Richard Knop
Richard Knop

Reputation: 83697

How to specify a method argument must be of certain class

So I have a class like this:

 class Encoder(object):

     movie = None

     def __init__(self, movie_instance):
         self.movie = movie_instance

     def encode_profile_hd(self):
         print "profile 1"

     def encode_profile_sd(self):
         print "profile 2"

How can I specify the movie_instance argument passed to the constructor must be of Movie class?

I tried:

def __init__(self, Movie movie_instance):

But that doesn't work. Sorry if this is obvious.

Upvotes: 0

Views: 831

Answers (5)

Charles Brunet
Charles Brunet

Reputation: 23120

You don't want to do that. What you should do is to document the requirements for your function. This way, somebody can build a different class and use it as argument to your function, as long as it implements required attributes.

An example of this are iterators. Any object with __iter__() or next() function can be used as an iterator. An other exemple is file object. Any object with attributes of a file can be used as a file in parameters of a function. StringIO is an example of such object.

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142126

The constructor is not __init__ it's __new__. Further note that __del__ is not a destructor.

Python's philosophy is duck-typing (unless using ABC's), which means everything that can behave as a duck and quacks like duck, could be a duck.

Explicitly type checking is against the data object model, and should be avoided unless you have a specific circumstance.

Upvotes: 0

mgilson
mgilson

Reputation: 309841

you can use isinstance for that.

def __init__(self,movie_instance):
    if(not isinstance(movie_instance, Movie)):
         raise ValueError("movie_instance must be an instance of class Movie")

This will work for Movie instances as well as anything that inherits from Movie.

It's worth noting that a lot of people would say that in Python, this idiom should not be used often. If something looks like a movie, smells like a movie (do movies have a scent?) and plays like a movie, why not just treat it like a movie? (In other words, try to use the object like a movie and handle the exception that is raised if it doesn't work).

Upvotes: 4

Sven Marnach
Sven Marnach

Reputation: 601489

Python usually relies on duck-typing, and it is considered bad style to artificially restrict the input parameters of your functions as this makes the code less flexible as it could be. Simply document the requirements clearly, and if the parameters do not conform to the requirements, the code will fail anyway.

Upvotes: 4

unwind
unwind

Reputation: 399753

Python is a dynamically typed language, you can't pre-declare the type of variables as you do in statically typed languages.

Upvotes: 1

Related Questions