def array.sum():
sm = 0
for a in array :
sm = sm + a
return sm
然后我想把这个函数称为:
x = [3, 5, 6]
y = x.sum() # = 14
答案 0 :(得分:3)
您可以在此处创建课程:
class my_array:
def __init__(self, lis):
self.array = lis
def sum(self):
sm = 0
for a in self.array :
sm += a
return sm #or simply use the built-in function `sum()`
...
>>> x = my_array([3,5,6])
>>> x.sum()
14
答案 1 :(得分:2)
class MyList(list):
def sum(self):
return sum(self)
然后:
MyList([1, 2, 3, 4, 5]).sum()
15
但是,我认为你不能完全按照自己的意愿行事,你应该使用内置的sum
功能:sum([1, 2, 3, 4, 5])