python - 难以理解类
问题描述
我觉得这是一个非常简单的概念,但我似乎无法将我的头脑围绕类并从它们返回值......这是我想出的尝试和实践的东西,非常 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")
解决方案
关于类约定的一些事情:
- 类的名称通常应以大写字母开头。
()
除非您使用继承,否则不需要在类名后面加上。
代码:
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
推荐阅读
- css - 无法使用 grunt 编译 Bootstrap css
- python - 在 Python for Mac 中创建一个 MessageBox?
- sql - 存储过程 Advantage Database SQL 中出现错误的意外令牌
- java - 如何使用 TextureAtlas 使用 LibGDX 创建动画?
- presto - 在 presto 中选择每月的第一天
- java - 如何使用 Spring Boot Rest Java EE 项目正确管理对文件的写入?
- javascript - 如何使用 ajax 使用 wcf 服务
- multithreading - Flask SocketIO Eventlet 第二次同时读取错误
- lua - love.graphics.polygon 中的坐标是什么意思
- r - 从具有特定固定宽度格式的数据框创建 txt 文件