我不知道为什么在尝试访问类中的函数时得到NameError
。
这是我遇到问题的代码。我想念什么吗?
class ArmstrongNumber:
def cubesum(num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(num):
if cubesum(num) == num:
return "Armstrong Number"
return "Not an Armstrong Number"
def Armstrong(num):
if cubesum(num) == num:
return True
return False
[i for i in range(1000) if ArmstrongNumber.Armstrong(i)] # this return NameError
错误消息:
NameError Traceback (most recent call last)
<ipython-input-32-f3d39f24a48c> in <module>
----> 1 ArmstrongNumber.Armstrong(153)
<ipython-input-31-fd21586166ed> in Armstrong(num)
10
11 def Armstrong(num):
---> 12 if cubesum(num) == num:
13 return True
14 return False
NameError: name 'cubesum' is not defined
答案 0 :(得分:2)
在方法前使用classname
class ArmstrongNumber:
def cubesum(num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(num):
if ArmstrongNumber.cubesum(num) == num:
return "Armstrong Number"
return "Not an Armstrong Number"
def Armstrong(num):
if ArmstrongNumber.cubesum(num) == num:
return True
return False
print([i for i in range(1000) if ArmstrongNumber.Armstrong(i)])
请避免将self
传递给那些不是instance methods
的函数。即使您在类中定义了该类,您仍然需要使用classname
访问它们。
答案 1 :(得分:0)
如果您真的想使用类,这应该是您的实际解决方案
class ArmstrongNumber(object):
def cubesum(self, num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(self, num):
if self.cubesum(num) == num:
return "Armstrong Number"
return "Not an Armstrong Number"
def Armstrong(self, num):
if self.cubesum(num) == num:
return True
return False
a = ArmstrongNumber()
print([i for i in range(1000) if a.Armstrong(i)])
输出
[0, 1, 153, 370, 371, 407]
第二种方法:
如果您不想使用类,请使用这样的静态方法
def cubesum(num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(num):
if cubesum(num) == num:
return "Armstrong Number"
return "Not an Armstrong Number"
def Armstrong(num):
if cubesum(num) == num:
return True
return False
# a = ArmstrongNumber()
print([i for i in range(1000) if Armstrong(i)])