继承的类对象未返回期望的结果(希望描述正确)

时间:2019-01-12 12:36:51

标签: python-3.x class oop inheritance

我正在使用Python学习OOP,并且正在尝试对模具对象(具有6个侧面)进行建模。我定义了一个继承自Die类的winnerDie(Die)类,我打算返回掷骰子以获取获胜值(6)的次数,并且我正在使用while循环。不幸的是,即使while循环正确迭代,它也始终返回0。

class Die(object):
    '''
    Simulate a generic die roll
    '''
    def __init__(self):
        '''Initialise the die, then roll it'''
        self._sides = 6 # A die has 6 sides. Underscore means it's private
        self._value = None # Its starting value is None (not 0)
        self.roll() # roll the die (the roll method is defined next)

    def roll(self):
        """Generate a random number from 0 and 6 (excluding 6)
        Then add 1 so that it's from 1 to 6
        Return this value"""
        import random
        self._value = 1 + random.randrange(self._sides)
        return self._value

    def __str__(self):
        """Define a string with a nice description of the object
        that is returned when using the print function"""
        return "Die with given %d sides, current value is %d."%(self._sides, self._value)

    def __repr__(self):
        """Defines a string with a nice representation of the object
        that is returned when the object is executed"""
        return "Die object\nNumber of sides: %f\nCurrent value: %f."%(self._sides, self._value)

class WinnerDie(Die):
    """Special case of die with value = 6 when rolled"""

    def __init__(self):
        super().__init__()
        self._count = 0
    def win(self):
        while self._value != 6:
            self._count += self._count
            print(self._count) # Added this for troubleshooting
            self.roll()
        return f"It takes {self._count} times to get the winning die"

请在此代码中我需要更正什么?

0 个答案:

没有答案