使用方法或if语句插入到实例变量中 (Python)

问题描述 投票:-1回答:2

我试图找出一个simmershorter的方式来添加到一个特定的实例变量.Ive有很难弄清楚什么,甚至谷歌,所以heres一个问题的说明。

Class Person:
      def __init__(self):
            self.year2018_sample_a = 0
            self.year2018_sample_b = 0
            self.year2019_sample_a = 0
            self.year2019_sample_b = 0
            self.year2020_sample_a = 0
            self.year2020_sample_b = 0

    #This works but not really ideal
    #we get the year from data, but didnt write the whole code

      def add_to_year(self...):
            if year == 2018 and sample == 'a':
               self.year2018_sample_a += 1
            elif year == 2018 and sample == 'b':
               self.year2018_sample_b += 1
            elif year == 2019 and sample == 'a':
               self.year2019_sample_a += 1
            etc......

有什么办法来写这个Wo有写每年两次? 下面的想法不工作,因为它只是一个字符串。但任何想法将是不错的。

      Pseudocode ideas:

      def add_to_year(..):
           datayear = get_from_data_column1
           datasample = get_from_data_column2

           self.f'year{datayear}_sample_{datasample}' += 1  -------This is the part where im 
                                                                  struggling to insert into changing 
                                                                  instance variables
python variables instance
2个回答
1
投票
Class Person:
    def __init__(self):
        self.samples = { year: { sample: 0 for sample in ('a', 'b') } for year in (2017,2018,2019) }

    def add_to(self, year, sample):
        self.samples[year][sample] += 1

instance = Person()
instance.add_to(2017, 'b')

0
投票

你可以使用 getattrsetattr:

class Foo():
    def __init__(self):
        for i in range(10):
            setattr(self, f'year_{2000 + i}', i)
f = Foo()
for i in range(10):
    print(getattr(f, f'year_{2000 + i}'))
print(f"Year 2005: {f.year_2005}")

产出:

0
1
2
3
4
5
6
7
8
9
Year 2005: 5
© www.soinside.com 2019 - 2024. All rights reserved.