我正在试图找到一种更简单/更短的方法来添加到特定的实例变量。 我很难弄清楚谷歌到底做了什么,所以这里有一个问题的例子:
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......
是否每年都要写两次呢? 下面的想法不起作用,因为它只是一个字符串。但任何想法都很好
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
您可以使用
getattr
和setattr
:输出:
相关问题 更多 >
编程相关推荐