【发布时间】:2018-03-27 10:18:02
【问题描述】:
我写了一个类来模拟掷骰子。我正在尝试实现私有方法 __check_dice(self) 以在创建类的实例时捕获错误以避免代码重复:
import numpy as np
class Dice():
""" Simulating the roll of a dice with possible outcomes ranging
from first_num to last_num (inclusive) """
def __init__(self, first_num=1, last_num=6):
self.first_num = first_num
self.last_num = last_num
def __check_dice(self):
if self.last_num >= self.first_num >= 0:
return True
else:
return "The first number should be smaller than the last.." \
"and both positive. I can't create your dice.."
def sides(self):
if __check_dice(self):
return "Our dice has {} sides". \
format(self.last_num + 1 - self.first_num)
def roll(self):
if __check_dice(self):
return "You rolled a " + \
str(np.random.choice(np.arange(self.first_num,
self.last_num + 1)))
dice_1 = Dice(-1, 18)
print(dice_1.sides())
print(dice_1.roll())
逻辑是当 __check_dice 计算结果为 True 时,如果调用以下两个方法,则可以执行。但是在运行代码时出现以下错误:
if __check_dice(self):
NameError: name '_Dice__check_dice' is not defined
为什么不能在另一个方法内的类范围内调用__check_dice方法? 我也尝试过不将方法设为私有,但我得到了类似的错误。
【问题讨论】:
-
因为
__check_dice是一个类方法,需要通过其类对象调用(本例为self)。将__check_dice(self)更改为self.__check_dice()。 -
我尝试过不使用私有方法,也尝试过 self.__check_dice()。不过似乎都没有发现错误..
标签: python python-3.x class oop private-methods