簡體   English   中英

python:為類實例變量名稱添加一個數字

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

我想計算班上的生日。 我想把年份作為類實例中的元素之一,如下所示:

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

無需迭代。 只需輸入:

self.year =年

因此,代碼將是:

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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM