Method's default parameter values are evaluated *once*

后端 未结 3 1700
广开言路
广开言路 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
    
    0 讨论(0)
  • 2020-12-06 18:18

    props should not have a default value like that. Do this instead:

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

    This is a common python "gotcha".

    0 讨论(0)
  • 2020-12-06 18:23

    The short version: Do this:

    class a(object):
        def __init__(self, props=None):
            self.props = props if props is not None else {}
    
    class b(a):
        def __init__(self, val = None):
            super(b, self).__init__()
            self.props.update({'arg': val})
    
    class c(b):
        def __init__(self, val):
        super(c, self).__init__(val)
    

    The long version:

    The function definition is evaluated exactly once, so every time you call it the same default argument is used. For this to work like you expected, the default arguments would have to be evaluated every time a function is called. But instead Python generates a function object once and adds the defaults to the object ( as func_obj.func_defaults )

    0 讨论(0)
提交回复
热议问题