从不同的父类调用方法(同名),但结果显示代码只运行其中一个

2021-10-17 16:59:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了三种骰子,然后用杯子包起来。Cup继承两个类(它们继承相同的基类)。在cup中,我从两个父类和基类中调用了三个roll方法。你知道吗

当我跑的时候纸杯卷,我应该得到三个数字,第一个是1-6,第二个是1-10,第三个是1-20。但是我运行了很多次,结果显示所有三个数字都在1-10之间,这意味着只有roll方法只能从父类中的一个派生。你知道吗

为什么会这样?如何解决这个问题?我只是从Python开始。你知道吗

更新

通过改变杯子的结构,解决了上述问题,但我有一个新问题。你知道吗

现在,代码运行良好,直到最后一部分输出结果时,应该有三个骰子返回的三个列表,但最后两个是空的,其中,滚动和求和时,它们不是空的。很奇怪。你知道吗

输出:

# >>> c = cup(2,3,4)
# 2 3 4
# >>> c.roll()
# (when print out roll in dices)
# [5, 2]
# [2, 6, 2]
# [6, 6, 2, 5]
# (but, when print out roll in cup, two become empty)
# [5, 2] [] []
# 36

代码:

class SixSidedDie:
    sides = 6
    valueLst = []
    sumVal = int()

    def __init__(self, nOfDie):
        self.nOfDie = nOfDie

    def roll(self):
        import random
        self.valueLst = []
        for i in range(1, self.nOfDie+1):
            self.valueLst.append(random.randint(1,self.sides))
        print(self.valueLst)
        return self.valueLst

    def sum(self):
        self.sumVal = 0
        for i in self.valueLst:
            self.sumVal += i
        return self.sumVal

    def getFaceValue(self):
        return self.valueLst

    def __repr__(self):
        return 'SixSidedDie({})'.format(self.faceValue)



class TenSidedDie(SixSidedDie):
    sides = 10          
    def __repr__(self):
        return 'TenSidedDie({})'.format(self.faceValue) 



class TwentySidedDie(SixSidedDie):

    sides = 20
    def __repr__(self):
        return 'TwentySidedDie({})'.format(self.faceValue) 





class cup():   

    sixSDLst = []
    tenSDLst = []
    twentySDLst = []

    def __init__(self, nOfSixSdDie = 1, nOfTenSdDie = 1, nOfTwentySdDie = 1):
        self.sixSdDie = SixSidedDie(nOfSixSdDie)
        self.tenSdDie = TenSidedDie(nOfTenSdDie)
        self.twentySdDie = TwentySidedDie(nOfTwentySdDie)
        print(nOfSixSdDie, nOfTenSdDie, nOfTwentySdDie)

    def roll(self):
        self.sixSDLst = self.sixSdDie.roll()
        self.tenSDlst = self.tenSdDie.roll()
        self.twentySDlst= self.twentySdDie.roll()
        print(self.sixSDLst,self.tenSDLst,self.twentySDLst)
        return self.sixSdDie.sum() + self.tenSdDie.sum() + self.twentySdDie.sum()

    def getSum(self):
        return self.sixSdDie.sum()+ self.tenSdDie.sum() + self.twentySdDie.sum()

    def __repr__(self):
        output = ''
        for i in self.sixSDLst:
            output = output + 'SixSidedDie(' + str(i) +'),'

        for j in self.tenSDLst:
            output = output + 'TenSidedDie(' + str(i) +'),'

        for k in self.twentySDLst[:-1]:
            output = output + 'TwentySidedDie(' + str(i) +'),'
        output = 'Cup(' + output + 'TwentySidedDie(' + str(self.twentySDLst[-1]) +')' + ')'
        return output

2条回答
网友
1楼 ·

首先,正如其他人所说,您使用继承是错误的,但我认为这是家庭作业的要求。你知道吗

在骰子子类中,尝试更新__init__方法中的边数:

class TenSidedDie(SixSidedDie):
    def __init__(self):
        self.sides = 10

    def __repr__(self):
       return 'TenSidedDie({})'.format(self.faceValue) 

此外,点名时,你不需要包括自己。你知道吗

for k in range(1, self.nOfTwentySdDie+1):
            self.fVOfTwentySdDie.append(TwentySidedDie.roll())

使用更新的代码:

对全局初始化列表进行注释对我很有用。你知道吗

另外,在打印信息时,您希望能够查看日志并立即理解它。我建议添加以下行滚动方法:print('Rolling [{}], count: [{}] values: {}'.format(self.sides, self.nOfDie, self.valueLst))这将告诉您要滚动的骰子的大小、数量以及每个骰子的结果。不再分析日志。你知道吗


因为你只是有技术问题,不要求你的家庭作业,这是我的代码,为我工作。我做了一些小的重写,使其更易于管理,并添加了日志记录:

import random

class SixSidedDie:
    sides = 6
    valueLst = []
    sumVal = int()

    def __init__(self, nOfDie):
        print('intializing d6 with [{}] dice'.format(nOfDie))
        self.nOfDie = nOfDie

    def roll(self):
        self.valueLst = []
        for i in range(1, self.nOfDie+1):
            self.valueLst.append(random.randint(1,self.sides))
        print('Rolling {} d{} values: {}'.format(self.nOfDie, self.sides, self.valueLst))
        return self.valueLst

    def sum(self):
        self.sumVal = 0
        for i in self.valueLst:
            self.sumVal += i
        return self.sumVal

    def getFaceValue(self):
        return self.valueLst

    def __repr__(self):
        return 'SixSidedDie({})'.format(self.faceValue)

class TenSidedDie(SixSidedDie):
    def __init__(self, nOfDie):
        print('intializing d10 with [{}] dice'.format(nOfDie))
        self.nOfDie = nOfDie
        self.sides = 10

    def __repr__(self):
        return 'TenSidedDie({})'.format(self.faceValue) 

class TwentySidedDie(SixSidedDie):
    def __init__(self, nOfDie):
        print('intializing d20 with [{}] dice'.format(nOfDie))
        self.nOfDie = nOfDie
        self.sides = 20

    def __repr__(self):
        return 'TwentySidedDie({})'.format(self.faceValue) 


class cup():

    def __init__(self, nOfSixSdDie = 1, nOfTenSdDie = 1, nOfTwentySdDie = 1):
        self.sixSdDie = SixSidedDie(nOfSixSdDie)
        self.tenSdDie = TenSidedDie(nOfTenSdDie)
        self.twentySdDie = TwentySidedDie(nOfTwentySdDie)

    def getSum(self):
        return self.sixSdDie.sum()+ self.tenSdDie.sum() + self.twentySdDie.sum()

    def roll(self):
        self.sixSdLst = self.sixSdDie.roll()
        self.tenSdLst = self.tenSdDie.roll()
        self.twentySdLst = self.twentySdDie.roll()
        return self.getSum()

    def __repr__(self):
        output = ''
        print('6 sided : [{}]\n10 sided: [{}]\n20 sided: [{}]'.format(len(self.sixSdLst), len(self.tenSdLst), len(self.twentySdLst)))
        for i in self.sixSdLst:
            output += 'SixSidedDie(' + str(i) +'),'
        output += '\n'

        for j in self.tenSdLst:
            output += 'TenSidedDie(' + str(j) +'),'
        output += '\n'

        for k in self.twentySdLst:
            output += 'TwentySidedDie(' + str(k) +'),'
        result = 'Cup(' + output + ')'
        return result


play_cup = cup(20, 20, 20)

print('ROLL:', play_cup.roll())
print('SUM:', play_cup.getSum())
print(play_cup)

结果:

intializing d6 with [5] dice
intializing d10 with [5] dice
intializing d20 with [5] dice
Rolling 5 d6 values: [1, 2, 2, 2, 3]
Rolling 5 d10 values: [6, 4, 5, 7, 3]
Rolling 5 d20 values: [9, 8, 2, 5, 10]
ROLL: 69
6 sided : [5]
10 sided: [5]
20 sided: [5]
[1, 2, 2, 2, 3]
[6, 4, 5, 7, 3]
[9, 8, 2, 5, 10]
Cup(SixSidedDie(1),SixSidedDie(2),SixSidedDie(2),SixSidedDie(2),SixSidedDie(3),
TenSidedDie(6),TenSidedDie(4),TenSidedDie(5),TenSidedDie(7),TenSidedDie(3),
TwentySidedDie(9),TwentySidedDie(8),TwentySidedDie(2),TwentySidedDie(5),TwentySidedDie(10),)

网友
2楼 ·

它之所以发生,是因为侧面是从TenSidedDie继承来的,然后你作为自己传递给每一卷。在print(self.sides)定义的开头添加cup,以查看它的实际操作。 从python class docs

class DerivedClassName(Base1, Base2, Base3):
   <statement-1>
    .
    .
    .
   <statement-N>

For most purposes, in the simplest cases, you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy. Thus, if an attribute is not found in DerivedClassName, it is searched for in Base1, then (recursively) in the base classes of Base1, and if it was not found there, it was searched for in Base2, and so on.

删除继承后,可以执行以下操作来解决:

 six_die =  SixSidedDie()
 for i in range(1, self.nOfSixSdDie+1):            
     self.fVOfSixSdDie.append(six_die.roll())  

相关问题