What better way to get around the “static variables” in Python?

后端 未结 3 538
情歌与酒
情歌与酒 2021-01-28 01:35

It seems that in Python, to declare a variable in a class, it is static (keeps its value in the next instances). What better way to get around this problem?

clas         


        
3条回答
  •  -上瘾入骨i
    2021-01-28 02:24

    Just leave the declaration out. If you want to provide default values for the variables, initialize them in the __init__ method instead.

    class Foo(object):
        def __init__(self):
            self.number = 0
    
        def set(self):
            self.number = 1
    
    >>> foo = Foo()
    >>> foo.number
    0
    >>> foo.set()
    >>> foo.number
    1
    >>> new_foo = Foo()
    >>> new_foo.number
    0
    

    Edit: replaced last line of the above snippet; it used to read 1 although it was just a typo on my side. Seems like it has caused quite a bit of confusion while I was away.

提交回复
热议问题