擅长:python、mysql、java
<p>您可以使用<a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a>。首先,假设参数是<code>X</code>类型,如果它们引发异常,那么假设它们是<code>Y</code>类型,依此类推:</p>
<pre><code>class Text(object):
def __init__(self, *init_vals):
try:
fileobjs = [open(fname) for fname in init_vals]
except TypeError:
# Then we consider them as file objects.
fileobjs = init_vals
try:
senteces = [parse_sentences(fobj) for fobj in fileobjs]
except TypeError:
# Then init_vals are Sentence objects.
senteces = fileobjs
</code></pre>
<p>注意,缺少类型检查意味着该方法实际上接受实现您实际使用的接口之一的任何类型(例如<code>file</code>-类对象,<code>Sentence</code>-类对象等)。在</p>
<p>如果你想支持很多不同的类型,这个方法会变得很重,但是我认为这是糟糕的代码设计。接受超过2,3,4个类型作为初始值设定项可能会让任何使用您的类的程序员感到困惑,因为他总是会想“等等,是不是<code>X</code>也接受了<code>Y</code>,或者是{<cd7>}接受了<code>Y</code>……”。在</p>
<p>最好将构造函数设计为只接受2,3个不同的<em>接口</em>,并向用户提供一些函数/类,允许用户将一些常用类型转换为这些接口。在</p>