Skip to content Skip to sidebar Skip to footer

Define Variables With The Same List Data But Different Objects Using Python

this is my code : attackUp = [10, 15,10, 15,10, 15] defenceUp = [10, 15,10, 15,10, 15] magicUp = [10, 15,10, 15,10, 15] attType = [1,1,1,1,1,1] weightDown = [10, 15,10, 15,10, 15]

Solution 1:

Well, a step in the right direction would be to create a base list and then copy it using slice notation:

base = [100, 100, 100, 100]
value_a = base[:]
value_b = base[:]

and so on. This doesn't gain you much for the shorter lists, but it should be useful for the longer ones at least.

But I think more generally, a richer data structure would be better for something like this. Why not create a class? You could then use setattr to fill up class members in a fairly straightforward way.

classWeapons(object):
    def__init__(self, base):
        for weapon in ["saber", "sword", "axe"]:
            setattr(self, weapon, base[:])

w = Weapons([100, 100, 100])
print w.__dict__  

#output: {'sword': [100, 100, 100], #         'saber': [100, 100, 100], #         'axe': [100, 100, 100]}

w.axe[0] = 10print w.axe       # output: [10, 100, 100]print w.sword     # output: [100, 100, 100]

Solution 2:

Define them all as empty arrays, then group the ones that need the same values into a list and iterate through that list, assigning the common values to each variable.

Solution 3:

You could do something like:

defaultAttack = [100, 100,100, 100,100, 100]
accAttackSword = list(defaultAttack)
accAttackSaber = list(defaultAttack)

The list() constructor makes a copy of the list, so they will be able to change independently.

Solution 4:

You can use list multiplication

accAttackSword = [100]*6
....
bookWeight = [100]*2
....

You might consider grouping all of the variables with similar prefixes either into dictionaries or nested lists (EDIT - or classes/objects). This could have benefits later for organization, and would allow you to iterate thru and set them all to the same initial values.

bookVars = ['AttackPhy', 'AttackMag', 'StrInstrument', 'StrCharms']
bookValues = dict()
for i in bookVars:
    bookValues[i] = [100]*2

And to access...

bookValues
  {'AttackMag': [100, 100], 'StrCharms': [100, 100], 'StrInstrument': [100, 100], 'AttackPhy': [100, 100]}
bookValues['AttackMag']
  [100, 100]

EDIT - check out senderle's thing too. at a glance his seems a little better, but id definitely consider using one of our ideas - the point is to structure it a little more. whenever you have groups of variables with similar prefixed names, consider grouping them together in a more meaningful way. you are already doing so in your mind, so make the code follow!

Post a Comment for "Define Variables With The Same List Data But Different Objects Using Python"