简体   繁体   English

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

[英]python: adding a number for the class instance variable name

I am trying to count birthdays within a class. 我想计算班上的生日。 I would like to have the year as one of the elements in the class instance like this: 我想把年份作为类实例中的元素之一,如下所示:

{'city': 'New York', '2000': 0}

...where '2000' increments with new data ...其中“ 2000”随着新数据而递增

But instead I can only get: 但是相反,我只能得到:

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

No need for iteration. 无需迭代。 Just type: 只需输入:

self.year = years self.year =年

So, code would be: 因此,代码将是:

class birthyear():
    def __init__(self,city,years):
        self.city = city
        self.year = years
    def yearCount(year):
        self.year += 1

Also, no need for list when you creating new instance. 另外,创建新实例时无需列表。

>>> bh = birthyear('Nis', 2000)
>>> bh.__dict__
{'city': 'nis', 'year': 2000}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM