This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Class static property not static
Type: behavior Stage: resolved
Components: Windows Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: chuyi, eric.smith, paul.moore, steve.dower, tim.golden, zach.ware
Priority: normal Keywords:

Created on 2019-10-15 07:36 by chuyi, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg354702 - (view) Author: 楚艺 (chuyi) Date: 2019-10-15 07:36
code:
------------------------------------------------------------------
    class D:
        num = 0
        
        def __init__(self):
            self.num += 1
            print('D num', self.num)

    for i in range(5):
        D()
---------------------------------------------------------------
console print:
---------------------------------------------------------------
Connected to pydev debugger (build 183.5429.31)
D num 1
D num 1
D num 1
D num 1
D num 1

Process finished with exit code 0
msg354706 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2019-10-15 07:47
When you assign to self.num, you're creating an instance variable which hides the class variable. Instead, assign directly to the class variable:

class D:
    num = 0
    def __init__(self):
        D.num += 1
        print('D num', self.num)

for i in range(5):
    D()

D num 1
D num 2
D num 3
D num 4
D num 5
History
Date User Action Args
2022-04-11 14:59:21adminsetgithub: 82662
2019-10-15 07:47:21eric.smithsetstatus: open -> closed

nosy: + eric.smith
messages: + msg354706

resolution: not a bug
stage: resolved
2019-10-15 07:36:40chuyicreate