2

simple explanations by examples would do where the 3 of them cannot be interchanged.

def __setitem__(self,**k):
        #self.val=k
        for key in k:
            self.val.setdefault(key,[]).extend(v for v in k[key])

Can the above step be done in iterations with setattr(obj,val[,can optional stuff come here??])

WHy not just create our own style and private methods?

def _add(self,**k):
    if isinstance(self, CClass):
        for key in k:
            self.val.setdefault(key,[]).extend(v for v in k[key])

Q: Where all a Class's scope allows these private methods to be accessed and used?

user2290820
  • 2,709
  • 5
  • 34
  • 62
  • 1
    Possible duplicate of https://stackoverflow.com/questions/10707206/what-is-the-difference-between-set-and-setattr-in-python-and-when-should – John Locke Jul 12 '20 at 22:32

1 Answers1

3

__setitem__ can only be used for setting one item:

def __setitem__(self, key, value):
    self.val.setdefault(key,[]).append(value)

If you prefer to extend all at once with one call, you can build something like dict's .update() method which takes an iterable and/or keyword arguments:

def update(self, it, **k):
    for key, val in it:
        self.val.setdefault(key,[]).extend(v for v in val)
    for key, val in k.iteritems():
        self.val.setdefault(key,[]).extend(v for v in val)
glglgl
  • 89,107
  • 13
  • 149
  • 217
  • so u mean my first code is really not extending but appending right? – user2290820 May 14 '13 at 12:16
  • @user2290820 I think extending should be ok, but you should obey that the correct semantic is used: what should happen if you do `my_object[key] = something`. – glglgl May 14 '13 at 12:24
  • because i want to extend to the current list,not overwrite or replace existing ones.im trying to find a way to add attributes dynamically.is there a way? – user2290820 May 14 '13 at 13:39