9.24.2011

Overloading constructor in Python

Python: コンストラクタのオーバーロード

・パラメータの型によって挙動を変える

1
2
3
4
5
6
7
class Widget():
  def __init__(self, arg):
    if isinstance(arg, int): print arg * 10
    elif isinstance(arg, basestring): print arg + '0'
 
Widget(1234# 12340
Widget('1234'# 12340

・パラメータの数によって挙動を変える

1
2
3
4
5
6
7
class Widget():
  def __init__(self, *args):
    if len(args) == 1: print '1 arg.'
    elif len(args) == 2: print '2 args.'
 
Widget(1# 1 arg.
Widget(1, 2# 2 args.

・個数と型を両方チェック

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Widget():
  def __init__(self, *args):
    def check(*types):
      if len(args) != len(types): return False
      for i, arg in enumerate(args):
        if not isinstance(arg, types[i]): return False
      return True
    if check(int): print args[0]
    elif check(int, int, basestring): print args[2]
    else: print 'other'
 
Widget(1# 1
Widget(1, 2, '3'# 3
Widget('3'# other

0 件のコメント:

コメントを投稿