我想创建一个类,并在该类中创建几个方法。我想要一种方法来获取列表并将其乘以一个数字,另一种方法来获取相同的数字并将其乘以列表。
我试图从 __ rmul __ 内部调用 __ mul __,因为它们使用相同的参数(列表和数字),但顺序相反。
class Asgard(object):
def __init__(self, list=0)
self.list = copy.deepcopy(list)
def __mul__(self, thor):
#multiplying list by integer
def __rmul__(self, loki):
self.__mul__(thor) #calling the method __mul__
为什么我不断收到错误消息“名称‘thor’未定义”? 一旦到达 __ rmul __ 方法,我如何告诉 Python 去使用 __ mul __ 方法?
最佳答案
在__rmul__
函数中没有thor
参数,只有一个loki
参数。
尝试使用该参数调用__mul__
:
class Asgard(object):
def __init__(self, list=0)
self.list = copy.deepcopy(list)
def __mul__(self, thor):
#multiplying list by integer
def __rmul__(self, loki):
self.__mul__(loki) #calling the method __mul__
关于python - 从同一个类中的另一个方法调用方法: which parameter is Python asking for?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47836792/