简体   繁体   中英

Use a method or if statement to insert into a instance variable (Python)

Im trying to figure out a simpler/shorter way to add to a specific instance variable. Ive had hard time figuring what even to google so heres a illustration of the problem:

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......

Is there anyway to write this w/o having to write every year twice? Idea below doesnt work as is, because it just a string. But any ideas would be nice.

      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
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')

You can use getattr and setattr :

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}")

Output:

0
1
2
3
4
5
6
7
8
9
Year 2005: 5

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