python:为类实例变量名添加一个数字

时间:2018-06-07 19:34:21

标签: python oop

我想在课堂上计算生日。我希望将年份作为类实例中的元素之一,如下所示:

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

1 个答案:

答案 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}