简体   繁体   English

根据Python中的另一个变量调用类变量

[英]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.) 其中teamA和teamB均为球队列表,“ w”为当前星期(1、2、3等)

I want to set a score, match, to one of the class variables based on what "w" is. 我想根据“ w”为一个类变量设置一个分数,匹配。 So if w=1, I want to set 'match' to i.w1. 因此,如果w = 1,我想将“ match”设置为i.w1。 If w=2, i.w2 = match. 如果w = 2,则i.w2 =匹配。 etc. The only way I can come up with to do this is having all 14 different if else statements, like so: 等。我想出的唯一方法是让所有14种不同的if语句,例如:

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? 并继续阅读14.有没有更简单,更有效的方法? 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. 然后,如果您知道要使用第一个元素,则可以使用文字self.w[0]来索引列表,如果您想要在变量中使用数字,则可以使用变量self.w[i]来为列表建立索引。

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. 这样,您的关键和价值是什么都不重要。

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

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