函数:add(a,b,*args)
功能:返回两个及以上的数值、字符串、列表、字典相加的结果
代码:
class ADD:
'override "add"'
def __init__(self):
return
@classmethod
def add(cls, a, b, *args):
# 数值
if type(a) in (int, float) and type(b) in (int, float):
s = a + b
for i in args:
assert type(i) in (int, float), 'error:code 1'
s += i
return s
# 字符串
elif type(a) == type(b) == str:
la, lb = list(a), list(b)
la.extend(lb)
for i in args:
assert type(i) == str, 'error:code 2'
la.extend(list(i))
return ''.join(la)
# 列表
elif type(a) == type(b) == list:
a.extend(b)
for i in args:
assert type(i) == list, 'error:code 3'
a.extend(i)
return a
# 字典
elif type(a) == type(b) == dict:
for k, v in b.items():
if k not in a.keys():
a[k] = v
for i in args:
assert type(i) == dict, 'error:code 4'
for k, v in i.items():
if k not in a.keys():
a[k] = v
return a
else:
assert False, 'type error.'
print(ADD.__doc__)
print(ADD.add(1,2.5,8,))
print(ADD.add('hello',' ','world','!'))
print(ADD.add([1,2,3],[4,5,6],[7,8,9]))
print(ADD.add({'1': 'a'}, {'2': 'b', '1': 'c'}, {'3': 'd'}))
运行结果:
说明:
字典相加为自定义,非正式
写成多态形式:
参考文章:面向对象之多态理解,多态的作用与好处 - NFC - 博客园 (cnblogs.com)
代码:
class ADD:
def __init__(self, a, b, *args):
self.a, self.b = a, b
self.args = args
def add(self): return
class AddFactory:
def __init__(self, a, b, *args):
self.a, self.b = a, b
self.args = args
def add(self):
a, b, args = self.a, self.b, self.args
if type(a) in (int, float) and type(b) in (int, float) and all([type(i) in (int, float) for i in args]):
na = NumberAdd(a, b, *args)
return na.add()
elif all([type(i) == str for i in args] + [type(a) == str, type(b) == str]):
sa = StrAdd(a, b, *args)
return sa.add()
elif all([type(i) == list for i in args] + [type(a) == type(b) == list]):
la = ListAdd(a, b, *args)
return la.add()
else:
assert False, 'type error.'
# 数值
class NumberAdd(ADD):
def __init__(self, a, b, *args):
super().__init__(a, b, *args)
def add(self):
s = self.a + self.b
for i in self.args:
s += i
return s
# 字符串
class StrAdd(ADD):
def __init__(self, a, b, *args):
super().__init__(a, b, *args)
def add(self):
la, lb = list(self.a), list(self.b)
la.extend(lb)
for i in self.args:
la.extend(list(i))
return ''.join(la)
# 列表
class ListAdd(ADD):
def __init__(self, a, b, *args):
super().__init__(a, b, *args)
def add(self):
self.a.extend(self.b)
for i in self.args:
self.a.extend(i)
return self.a
if __name__ == '__main__':
numbers = AddFactory(4.5, 5.5, 2, )
strs = AddFactory('hello', ' ', 'world', '!')
lists = AddFactory([1, 2], [3, 4], [5])
print(numbers.add())
print(strs.add())
print(lists.add())
运行结果: