首页 > 解决方案 > 难以理解类

问题描述

我觉得这是一个非常简单的概念,但我似乎无法将我的头脑围绕类并从它们返回值......这是我想出的尝试和实践的东西,非常 WIP,但我被困在这里. 提前致谢

import random
global d6

print("welcome to fight night")

#dice roll
class die():
    def __init__(self, sides):
        self.sides = sides

    def roll(self):
        chance = random.randint(1,self.sides)
        if chance == 3:
         return True
    if chance != 3:
         return False
d6 = die(6)

class Player():
    def __init__(self, name, weight, spec):
        self.name = name
        self.weight = weight
        self.spec = spec


fighter1 = Player("BRUCE LEE", 150, "SUPER SPEED")
fighter2 = Player(GEORGE FORMAN", 225, "REACH")


## how do i return true or false here to check hit?
print(fighter1(name) + "attacks"+ fighter2(name))
d6.roll()
if d6 == True:
    print(fighter(name) + "hit" + fighter2(name))
if d6 == False:
    print("attack missed")

标签: pythonpython-3.x

解决方案


关于类约定的一些事情:

  • 类的名称通常应以大写字母开头。
  • ()除非您使用继承,否则不需要在类名后面加上。

代码:

class Die:

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

    def roll(self):
        """
        Returns True if the roll succeeds, returns False otherwise.
        There is a (1 / self.number_of_sides) chance the roll will succeed.
        """
        from random import choice
        return choice([True] + [False] * (self.number_of_sides-1))

die = Die(6)

if die.roll():
    print("Nice!")
else:
    print("Sorry, try again.")

编辑我认为您需要一个更基本的return关键字如何工作的示例:

def give_me_a_number():
    return 5 + 4

x = give_me_a_number()
print(x)

输出:

9

推荐阅读