1

質問:

  1. Pythonはメソッドをそのようにロードしますか?誰が最後に来て誰が勝ちますか?2つのメソッドが正確な名前を共有している場合でも、引数が異なっていても(シグネチャが異なっていても)、最後のメソッドは実行時エラーを発生させることなく、とにかく前のすべてのメソッドを無効にしますか?
  2. Pythonにオーバーロードがない場合、JAVAのようにオーバーロードを行うためのPython推奨の方法は何ですか?

以下の例:

class Base(object):
    def __init__(self):
        print "Base created without args"
    def __init__(self, a):
        print "Base created " + a + "\n"

print Base("test")私に与える:

Base created test

<__main__.Base object at 0x1090fff10>

print Base()私に与えている間:

Traceback (most recent call last):
File "${path to super file}/super.py", line 27, in <module>
print Base()
TypeError: __init__() takes exactly 2 arguments (1 given)
4

2 に答える 2

4
  1. 基本的に、あなたはすでにその質問に自分で答えています。Pythonはメソッドのシグネチャを気にせず、名前だけが重要です。これは、モジュールレベルの関数にも当てはまります。
  2. Javaとは異なり、Pythonではメソッド引数のデフォルト値を指定できます(私の意見でははるかに便利です)。

    class Base(object):
        def __init__(self, a=None):
            if a is None:
                print "Base created without args."
            else:
                print "Base created with %s" % a
    
    a = Base()    # prints "Base created without args."
    b = Base(123) # prints "Base created with 123."
    
于 2013-03-18T20:20:55.967 に答える
1

デコレータを使用して、独自のメソッドオーバーロードをロールできます。

class OverloadFunction(object):

    def __new__(cls, f):
        self = object.__new__(cls)
        setattr(self, "_dct", {})
        return self.overload(())(f)

    def overload(self, signature):
        def wrapper(f):
            self._dct[signature] = f
            return self
        return wrapper

    def __call__(self, *args, **kwargs):
        return self._dct[self._get_signature(args)](*args, **kwargs)

    def _get_signature(self, obj):
        return tuple(type(x) for x in obj)


@OverloadFunction
def hello():
    print "hello, no args"

@hello.overload((int,))
def hello(i):
    print "hello with an int argument:", i

@OverloadFunction
def add(): pass

@add.overload((int, int))
def add(a, b):
    print "integer addition, %d + %d = %d" % (a, b, a + b)

@add.overload((str, int))
def add(a, b):
    print "string concatentation, %r + %d = %r" % (a, b, a + str(b))

hello()
hello(1)
add(2, 3)
add("a", 3)

どの出力:

hello, no args
hello with an int argument: 1
integer addition, 2 + 3 = 5
string concatentation, 'a' + 3 = 'a3'
于 2013-03-18T20:58:47.677 に答える