Method's default parameter values are evaluated *once*

后端 未结 3 1709
广开言路
广开言路 2020-12-06 17:39

I\'ve found a strange issue with subclassing and dictionary updates in new-style classes:

Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit          


        
3条回答
  •  执笔经年
    2020-12-06 18:14

    Your problem is in this line:

    def __init__(self, props={}):
    

    {} is an mutable type. And in python default argument values are only evaluated once. That means all your instances are sharing the same dictionary object!

    To fix this change it to:

    class a(object):
        def __init__(self, props=None):
            if props is None:
                props = {}
            self.props = props
    

提交回复
热议问题