我想在课堂上计算生日。我希望将年份作为类实例中的元素之一,如下所示:
{'city': 'New York', '2000': 0}
......其中' 2000'使用新数据递增
但我只能得到:
{'city': 'New York', 'year': 2000}
class birthyear():
def __init__(self,city,year):
self.city = city
#Why can't I do it 'manually' like so?:
#self.'2000' = 0
#Of course this works, but it is not what I need for further incrementing
self.year = year
by = birthyear('New York',2000)
print (by.__dict__)
答案 0 :(得分:0)
无需迭代。只需输入:
self.year = years
所以,代码将是:
class birthyear():
def __init__(self,city,years):
self.city = city
self.year = years
def yearCount(year):
self.year += 1
此外,创建新实例时无需列表。
>>> bh = birthyear('Nis', 2000)
>>> bh.__dict__
{'city': 'nis', 'year': 2000}