简体   繁体   中英

Calling class variable based on another variable in Python

I have this code for this class:

class TeamID:
    def __init__(self, name, ID, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, wins, losses, pr):
        self.name = name
        self.ID = ID
        self.w1 = w1
        self.w2 = w2
        self.w3 = w3
        self.w4 = w4
        self.w5 = w5
        self.w6 = w6
        self.w7 = w7
        self.w8 = w8
        self.w9 = w9
        self.w10 = w10
        self.w11 = w11
        self.w12 = w12
        self.w13 = w13
        self.w14 = w14
        self.wins = wins
        self.losses = losses
        self.pr = pr

I also have this separate function:

def scores(teamA, teamB, w):
    for a,b in zip(teamA,teamB):
        for i in AllTeams:
            if a == i.name:
                match = [item.text for item in soup.findAll("div", { "class" : "danglerBox totalScore" })]

Where teamA and teamB are both a list of teams, with 'w' being the current week (1, 2, 3, etc.)

I want to set a score, match, to one of the class variables based on what "w" is. So if w=1, I want to set 'match' to i.w1. If w=2, i.w2 = match. etc. The only way I can come up with to do this is having all 14 different if else statements, like so:

if w == 1:
    i.w1 = match
elif w == 2:
    i.w2 = match
elif w == 3:
    i.w3 = match

and keep going through 14. Is there an easier, more efficient way of doing this? I tried the following, but clearly it doesn't work:

i.w + '%s' % (w) = match

Any time you find yourself wanting a handful of variables, all of which are the same, except with different number suffixes, it means you actually want a list.

Then you can index the list either with a literal, self.w[0] if you know you want the first element, or with a variable, self.w[i] if you have the number you want in a variable.

A way to do this is using a dictionary. Now a list have been suggested, but counting on your variables to have a certain naming convention, that matches indexes is a bit unsafe, and could potentially force you into using an unwanted data structure later on. A dictionary is a bit more flexible when it comes to that:

dct = {}
dct[1] = w1
dct[2] = w2
dct[3] = w3
#ect...

And then when you want to use it, you can just do something like this:

match = dct[w]

This way it doesnt really matter what your key and value is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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