对于可以使用两个不同的单参数构造函数初始化的类,这是正确的做法吗?假设参数可以是字符串或int:
def __init__(self,param):
if(isinstance(param,basestring)):
#Initialize using param (string)
elif(isinstance(param,int)):
#Initialize using param (int)
else:
raise Exception("Invalid param type - must be int or string.")
答案 0 :(得分:0)
我认为你可以在python 3.4中使用functools.singledispatch
做一些有趣的事情。但事实证明它有点麻烦。
from functools import singledispatch
class A:
def __init__(self, first_arg, another_arg=None):
A._init(first_arg, self, another_arg)
@singledispatch
def _init(arg0, self, arg1):
raise TypeError(arg0)
@_init.register(int)
def _init_int(arg0, self, arg1):
print('_init_int', arg0, arg1)
self.arg = arg0
@_init.register(str)
def _init_str(arg0, self, arg1):
print('_init_str', arg0, arg1)
self.arg = arg0
A(1)
A('str')
class MyInt(int):
pass
A(MyInt(3))
A([])
产生
_init_int 1 None
_init_str str None
_init_int 3 None
Traceback (most recent call last):
File "multi_init.py", line 32, in <module>
A([])
File "multi_init.py", line 8, in __init__
A._init(first_arg, self, another_arg)
File "/usr/lib/python3.4/functools.py", line 707, in wrapper
return dispatch(args[0].__class__)(*args, **kw)
File "multi_init.py", line 12, in _init
raise TypeError(arg0)
TypeError: []