Python Class Members Initialization

前端 未结 5 1770
后悔当初
后悔当初 2020-11-29 03:37

I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I\'m a long time C++ programmer,

5条回答
  •  不知归路
    2020-11-29 04:32

    What you keep referring to as a bug is the documented, standard behavior of Python classes.

    Declaring a dict outside of __init__ as you initially did is declaring a class-level variable. It is only created once at first, whenever you create new objects it will reuse this same dict. To create instance variables, you declare them with self in __init__; its as simple as that.

提交回复
热议问题