Python 2.x gotchas and landmines

后端 未结 23 2349
北恋
北恋 2020-11-28 17:47

The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things sp

23条回答
  •  旧时难觅i
    2020-11-28 18:29

    Using class variables when you want instance variables. Most of the time this doesn't cause problems, but if it's a mutable value it causes surprises.

    class Foo(object):
        x = {}
    

    But:

    >>> f1 = Foo()
    >>> f2 = Foo()
    >>> f1.x['a'] = 'b'
    >>> f2.x
    {'a': 'b'}
    

    You almost always want instance variables, which require you to assign inside __init__:

    class Foo(object):
        def __init__(self):
            self.x = {}
    

提交回复
热议问题