1

Using a class to create several instances in a dictionary, their attribute is not unique. I'd like each of them to have their own unique attribute. How do you do this?

code:

class a(object):

    attr_a = {}

    def __init__(self, a={}):

        self.attr_a = a

if __name__ == '__main__':

    b = a()
    c = a()
    b.attr_a['abc'] = 'abc'
    c.attr_a['abc'] = 'def'

    print(b.attr_a)
    print(c.attr_a)

result:

{'abc': 'def'}
{'abc': 'def'}

wanted result:

{'abc': 'abc'}
{'abc': 'def'}
Lance Roberts
  • 22,383
  • 32
  • 112
  • 130
xielingyun
  • 780
  • 9
  • 17

1 Answers1

2

Two problems here:

1) For instance-level attributes, as opposed to class-level attributes, don't declare at the class level. So, remove the attr_a = {} in your class.

2) The default value a={} is evaluated at class/function declaration time, as opposed to instance-creation/function-call time, so rarely should you use a mutable object as a default value. This causes all instances of your class that are created with the default a value to share the same attr_a dict. You should use a=None as your default value, and then instantiate it inside of __init__ instead, like this:

def __init__(self, a=None):
        self.attr_a = a or {}
tom
  • 18,953
  • 4
  • 35
  • 35
  • 1
    Don't use `a or {}`. What if someone passed in a reference to an empty dict or any other falsy value? It's much better to avoid laziness and do: `self.attr_a = {} if a is None else a`. (and document the fact that `None` is the sentinel value you're using). – mgilson Feb 18 '13 at 04:54
  • @mgilson:thx, somebody suggest:`if not a: a = {}; self.attr_a = {}` – xielingyun Feb 18 '13 at 05:32
  • @mgilson, point taken! – tom Feb 18 '13 at 19:26