0

所以我有这样的课:

 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"

如何指定传递给构造函数的 movie_instance 参数必须是 Movie 类?

我试过了:

def __init__(self, Movie movie_instance):

但这不起作用。对不起,如果这很明显。

4

5 回答 5

4

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.

于 2012-06-28T14:41:12.050 回答
3

你可以使用isinstance它。

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

这将适用于Movie实例以及任何继承自Movie.

值得注意的是,很多人会说,在 Python 中,这个习语不应该经常使用。如果某些东西看起来像电影,闻起来像电影(电影有气味吗?)并且像电影一样播放,为什么不把它当作电影呢?(换句话说,尝试像电影一样使用该对象,并处理如果它不起作用而引发的异常)。

于 2012-06-28T14:35:26.073 回答
1

Python 是一种动态类型语言,您不能像在静态类型语言中那样预先声明变量的类型。

于 2012-06-28T14:38:05.717 回答
0

构造函数不是__init__it's __new__。进一步注意,__del__它不是析构函数。

Python 的哲学是鸭子类型(除非使用 ABC),这意味着所有可以表现得像鸭子和像鸭子一样嘎嘎叫的东西都可能是鸭子。

显式类型检查违反数据对象模型,除非您有特定情况,否则应避免。

于 2012-06-28T14:46:35.537 回答
0

你不想那样做。您应该做的是记录您的功能的要求。这样,只要实现了所需的属性,某人就可以构建一个不同的类并将其用作函数的参数。

一个例子是迭代器。任何具有__iter__()ornext()函数的对象都可以用作迭代器。另一个例子是文件对象。任何具有文件属性的对象都可以用作函数参数中的文件。StringIO是此类对象的一个​​示例。

于 2012-06-28T14:49:14.287 回答