2017-02-12 79 views
1

我有一個簡單的類,我每次創建該類的實例時,我想的類變量來增加我應該怎麼做,與此代碼:遞增類變量動態地在Python

class Person: 

    person_count = 0 

    def __init__(self, username): 
     self.username = username 

ashley = Person("Ash") 
daphne = Person("Daph") 

Person.person_count #I want this to be 2 

回答

4

簡單地增加類變量__init__

class Person(object): 

    person_count = 0 

    def __init__(self, username): 
     self.username = username 
     Person.person_count += 1 # here 

ashley = Person("Ash") 
daphne = Person("Daph") 

print(Person.person_count) 
# 2 

而且不要忘記從object子類,如果你對Python的2

What is the purpose of subclassing the class "object" in Python?

1

你將不得不內增加類的變量__init__爲:

class Person: 
    person_count = 0 
    def __init__(self, username): 
     self.username = username 
     self.__class__.person_count += 1 
     # OR, 
     # Person.person_count += 1 

例子:

>>> Person.person_count 
2 

>>> ashley = Person("Ash") 
>>> ashley.person_count 
1 
>>> daphne = Person("Daph") 
>>> daphne.person_count 
2 

,您也可以直接使用類作爲提取數

0

使用__init__方法以便在弄皺你的類變量:

class Person: 
    person_count = 0 
    def __init__(self, username): 
     self.username = username 
     Person.person_count += 1 

類變量可以使用類的名稱訪問,所以在這種情況下Person。請記住,您也可以從實例訪問此類變量,因此:

>>> p1 = Person('person1') 
>>> Person.person_count 
1 
>> p1.person_count 
1 
>> p2 = Person('person2') 
>>> Person.person_count 
2 
>> p1.person_count 
2 
>> p2.person_count 
2