beginner question about python -


the following code doesn't perform how expected , can't figure out why. i'm relatively new python , confused. both times display x.attributes they're set 0. shouldn't rollstats() updating them?

import random  def roll(size):         return random.randint(1, size)  class lifeform:         def __init__(self, name):                 self.name = name                 self.attributes = { 'str': 0, 'dex': 0, 'con': 0, 'int': 0, 'wis': 0, 'cha': 0, }          def rollattribute(self):                 # roll 4 6sided di                 d1 = roll(6)                 d2 = roll(6)                 d3 = roll(6)                 d4 = roll(6)                  # discard lowest roll                 if d1 < d2 , d1 < d3 , d1 < d4:     total = d2 + d3 + d4                 elif d2 < d1 , d2 < d3 , d2 < d4:   total = d1 + d3 + d4                 elif d3 < d1 , d3 < d2 , d3 < d4:   total = d1 + d2 + d4                 else:                                   total = d1 + d2 + d3                  return total          def rollstats(self):                 self.attributes['str'] = self.rollattribute()                 self.attributes['dex'] = self.rollattribute()                 self.attributes['con'] = self.rollattribute()                 self.attributes['int'] = self.rollattribute()                 self.attributes['wis'] = self.rollattribute()                 self.attributes['cha'] = self.rollattribute() x = lifeform("test") print x.attributes x.rollstats() print x.attributes 

edit: here's output btw

$ python fight.py {'dex': 0, 'cha': 0, 'int': 0, 'wis': 0, 'str': 0, 'con': 0} {'dex': 0, 'cha': 0, 'int': 0, 'wis': 0, 'str': 0, 'con': 0} 

(i had typo in code spelling "wis" "wiz", corrected problem still exists)

i random values on each run.

as style, can shrink code considerably:

class lifeform:     def __init__(self, name):         self.name = name         self.attributes = { 'str': 0, 'dex': 0, 'con': 0, 'int': 0, 'wiz': 0, 'cha': 0, }      def rollattribute(self):          # roll 4 6sided di         dice = [roll(6) in range(4)]          # discard lowest roll         return sum(dice) - min(dice)      def rollstats(self):         key in self.attributes:             self.attributes[key] = self.rollattribute() 

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -