我在python opp的多重继承中得到类型错误

moiiocjp  于 2022-12-27  发布在  Python
关注(0)|答案(2)|浏览(191)
import  random

class Coin:
    def flip(self):
        #toss=int(input('how many times you want to tosses the coin?: '))
        for i in range(self):
            rand=random.randint(-1,1)
            if rand==1:
                return rand
                #print("head")
            else:
                return rand
                #print('tail')
    print(flip(4))

class Dice:
    def roll(self):
        #x=int(input("inter number"))
        for x in range(self):
            points=random.randint(1,6)
            return points
    print(roll(5))

class Player(Coin,Dice):
    def rolls(self):
        # x=int(input("inter number"))
        for x in range(self):
            points = random.randint(1, 6)
            return points

    print(rolls(5))

obj=Player()
obj.flip()
obj.roll()

运行代码后,我得到的类型错误为TypeError:'Player'对象不能被解释为整数“我想做一个程序,它将继承Coin和Dice类,在Player类中,我将给予一些条件,如如果flip=head,则它将向前移动并从初始位置更新位置。

n6lpvg4x

n6lpvg4x1#

for x in range(self):函数需要一个整数(或多个整数)作为参数,但您传递的是类本身的示例(通过self参数),从而导致您遇到TypeError
根据注解掉的input调用,我猜您的意思是输入一个数字,然后将该数字传递给for循环的range函数:

class Coin:
    def flip(self):
        toss=int(input('how many times you want to tosses the coin?: '))
        for i in range(toss):
            rand=random.randint(-1,1)
            if rand==1:
                return rand
                #print("head")
            else:
                return rand
                #print('tail')
    print(flip(4))

class Dice:
    def roll(self):
        x=int(input("Enter number"))
        for i in range(x):
            points=random.randint(1,6)
            return points
    print(roll(5))

class Player(Coin,Dice):
    def rolls(self):
        x=int(input("Enter number"))
        for i in range(x):
            points = random.randint(1, 6)
            return points

    print(rolls(5))

你可以(并且应该)阅读更多关于Python here中的类的内容,但是我认为您可能误解了如何在Python中使用self。(根据命名约定)类示例方法中的参数引用类自身的示例,因此在您的情况下,当您执行obj.flip()时,self将引用示例化的Player类的示例(换句话说,obj)。因此,尝试将此参数传递给range函数时,将导致TypeError: 'Player' object cannot be interpreted as an integer

ecbunoof

ecbunoof2#

class Coin:
    def flip(self):
        toss=int(input('how many times you want to tosses the coin?: '))
        for i in range(toss):
            rand=random.randint(-1,1)
            if rand==1:
                return rand
                #print("head")
            else:
                return rand
                #print('tail')
    print(flip(4))

class Dice:
    def roll(self):
        x=int(input("Enter number"))
        for i in range(x):
            points=random.randint(1,6)
            return points
    print(roll(5))

class Player(Coin,Dice):
    def rolls(self):
        x=int(input("Enter number"))
        for i in range(x):
            points = random.randint(1, 6)
            return points

    print(rolls(5))

相关问题