简体   繁体   English

理解Python类实例

[英]Understanding Python Class instances

I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. 我正在研究一个使用python类的问题,并且有一个构造函数来给出一个die的边数和一个用于根据边数返回的随机数掷出die的函数。 I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. 我意识到代码是非常基本的,但是我很难理解如何总结三个不同侧面的掷骰子。 Since a variable is passing the function instance what would be the best way to grab that value to add it up? 由于变量正在传递函数实例,因此获取该值的最佳方法是什么? Here is what I have. 这就是我所拥有的。

*To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. *澄清......我可以将roll1.roll_dice()的总数加起来,但我必须单独显示每个掷骰子,然后显示三个骰子的总数。 I can do either one of those but not both. 我可以做其中任何一个但不是两个。

class Die():

        def __init__(self, s = 6):
            self.sides = s
        def roll_die(self):
            x = random.randint(1,self.sides)
            return x

        roll1 = Die()   #Rolling die 1 with the default side of 6
        roll2 = Die(4)  #Rolling die 2 with 4 sides
        roll3 = Die(12) #Rolling die 3 with 12 sides

        print roll1.roll_die()  
        print roll2.roll_die()
        print roll3.roll_die()

You can store the results in a list: 您可以将结果存储在列表中:

rolls = [Die(n).roll_die() for n in (6, 4, 12)]

then you can show the individual results 然后你可以显示个别结果

>>> print rolls
[5, 2, 6]

or sum them 或者总结一下

>>> print sum(rolls)
13

Or, instead, you could keep a running total: 或者,相反,您可以保持总计:

total = 0
for n in (6, 4, 12):
    value = Die(n).roll_die()
    print "Rolled a", value
    total += value
print "Total is", total

(edited to reflect the changes/clarifications to the question) (编辑以反映对问题的更改/澄清)

I'm not sure exactly where you're confused. 我不确定你到底困惑的确切位置。 The simplest thing you need to do is separate the concept of a specific die you're going to roll (the object) with the action (rolling it). 您需要做的最简单的事情是将您要滚动的特定骰子(对象)的概念与动作(滚动它)分开。 I would start here: 我会从这里开始:

d6 = Die() #create die 1 with the default side of 6
d4 = Die(4) #create die 2 with 4 sides
d12 = Die(12) #create die 3 with 12 sides

roll1 = d6.roll_die()
roll2 = d4.roll_die()
roll3 = d12.roll_die()

print "%d\n%d\n%d\nsum = %d" % (roll1, roll2, roll3, roll1 + roll2 + roll3)

... and then get fancier with lists, etc. ...然后用列表等获得更多的爱好者

It may also be useful to just store the last roll so you can get it whenever you want. 仅存储最后一卷也可能很有用,这样您就可以随时获取它。

def __init__(self, s = 6):
    self.sides = s
    self.last_roll = None

def roll_die(self):
    self.last_roll = random.randint(1,self.sides)
    return self.last_roll

Since roll_die returns a value, you can add those values. 由于roll_die返回一个值,您可以添加这些值。

Try this. 尝试这个。

roll1.roll_die() + roll2.roll_die()

What happens? 怎么了?

You can just sum the numbers. 你可以把数字加起来。 In case you want to sum the outcome of n rolls, consider adding this function to the class: 如果您想要总结n个卷的结果,请考虑将此函数添加到类中:

def sum_of_n_rolls(self, n)
    return sum(self.roll_die() for _ in range(n))

Also, consider renaming roll_die to just roll . 另外,考虑将roll_die重命名为roll It's obvious that it's not about rolling a rock, since the method is part of the class Die . 显而易见的是,这不是关于滚动岩石,因为该方法是Die类的一部分。


Edit : I now read you need to print intermediate rolls. 编辑 :我现在读到你需要打印中间卷。 Consider: 考虑:

def n_rolls(self, n):
    return [self.roll_die() for _ in range(n)]

Now you can roll a 7-sided die 10 times: 现在你可以滚动7面模具10次:

rolls = Die(7).n_rolls(10)
print(rolls, sum(rolls))

Guess I'd do something like this: 猜猜我会这样做:

# Create dice
sides = [6,4,12]
dice = [Die(s) for s in sides]

# Roll dice
rolls = [die.roll_die() for die in dice]

# Print rolls
for roll in rolls:
    print roll

You can also combine a few of these steps if you like: 如果您愿意,还可以结合以下几个步骤:

for num_sides in [6,4,12]:
    print Die(num_sides).roll_die()

If I understood you correctly you want a class attribute. 如果我理解正确你想要一个类属性。

UPDATE: Added a way for automatically reseting the total 更新:添加了一种自动重置总数的方法

import random

class Die():
    _total = 0

    @classmethod
    def total(cls):
        t = cls._total
        cls._total = 0
        return t

    def __init__(self, s=6):
        self.sides = s

    def roll_die(self):
        x = random.randint(1,self.sides)
        self.__class__._total += x
        return x

roll1 = Die()   #Rolling die 1 with the default side of 6
roll2 = Die(4)  #Rolling die 2 with 4 sides
roll3 = Die(12) #Rolling die 3 with 12 sides

print roll1.roll_die()  
print roll2.roll_die()
print roll3.roll_die()
print Die.total()
print "--"
print roll1.roll_die()  
print roll2.roll_die()
print roll3.roll_die()
print Die.total()

Let's get crazy :) (combined with my last answer as well) 让我们变得疯狂:)(结合我的上一个答案)

class Die():
    def __init__(self, s = 6):
        self.sides = s
        self.last_roll = None

    def roll_die(self):
        self.last_roll = random.randint(1,self.sides)
        return self.last_roll

dice = map(Die, (6, 4, 12))
rolls = map(Die.roll_die, dice)

print rolls
print sum(rolls)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM