I am creating a custom class for my project which is a recursive list of dictionaries. The attribute my_list is a list of dictionaries in which case I want to iterate over each of the keys, in each of the dictionaries, within the one object.  The code below is my current attempt. I have seen this solution  which gets the same error message but the difference is I want to iterate within a class not over all the objects of a particular class.  class List_of_dicts:      def __init__(self):         self.my_list = []      def add(self, item: dict):         self.my_list.append(item)   l = List_of_dicts() l.add({'a': 1, 'b': 2}) l.add({'c': 3, 'd': 4})  for obj in l:     print(obj.key)   I get this error:  TypeError: 'List_of_dicts' object is not iterable   I expect the iteration to be over the keys: a, b, c, d, in that order.  How do I implement the iterative behaviour which will allow me to iterate over a class like this?
15288
How would one create an iterative function (or iterator object) in python?
82657
I want to override access to one variable in a class, but return all others normally.  How do I accomplish this with __getattribute__?  I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error:  class D(object):     def __init__(self):         self.test=20         self.test2=21     def __getattribute__(self,name):         if name=='test':             return 0.         else:             return self.__dict__[name]  &gt;&gt;&gt; print D().test 0.0 &gt;&gt;&gt; print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp
53471
Now that it's clear , there is an associated concept that I use all the time without knowing what it really means.   I suppose everybody made once a mistake with parenthesis, resulting  in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for.  Could you give me some explanations, including examples with the magic method ?
70482
Which types of classes can use foreach loops?
91303
The following seems strange.. Basically, the somedata attribute seems shared between all the classes that inherited from the_base_class.  class the_base_class:     somedata = {}     somedata['was_false_in_base'] = False   class subclassthing(the_base_class):     def __init__(self):             print self.somedata   first = subclassthing() {'was_false_in_base': False} first.somedata['was_false_in_base'] = True second = subclassthing() {'was_false_in_base': True} &gt;&gt;&gt; del first &gt;&gt;&gt; del second &gt;&gt;&gt; third = subclassthing() {'was_false_in_base': True}   Defining self.somedata in the __init__ function is obviously the correct way to get around this (so each class has it's own somedata dict) - but when is such behavior desirable?
98138
In Python, I can do:  &gt;&gt;&gt; list = ['a', 'b', 'c'] &gt;&gt;&gt; ', '.join(list) 'a, b, c'   Is there any easy way to do the same when I have a list of objects?  &gt;&gt;&gt; class Obj: ...     def __str__(self): ...         return 'name' ... &gt;&gt;&gt; list = [Obj(), Obj(), Obj()] &gt;&gt;&gt; ', '.join(list) Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: sequence item 0: expected string, instance found   Or do I have to resort to a for loop?
100856
Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:  &gt;&gt;&gt; class Foo: ...     bar = 'hello' ...     baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' }   NOTE: It should not include methods. Only fields.
17232
Hi i'm thying threading with bpy this is my code:  import bpy import threading   class Cubes(threading.Thread):      def __init__(self):         threading.Thread.__init__(self)       def run(self):          scale = 0.2         space = 0.2         max_range = 6           for i in range(0, max_range):              bpy.ops.mesh.primitive_cube_add(radius = 1, location=(0, 0, 1))             bpy.ops.object.origin_set( type="ORIGIN_CURSOR" )              bpy.context.active_object.scale.x = scale             bpy.context.active_object.scale.y = scale             bpy.context.active_object.scale.z = 5              bpy.ops.object.transform_apply(location = False, rotation = False, scale = True)             bpy.context.active_object.location = (((i*scale*2)+(i*space))-(((max_range*scale*2)+(max_range*space)))/2,0,0)           return  t = Cubes() t.start()   but when i run this the console give me this error:  Exception in thread Thread-1: Traceback (most recent call last):   File "C:\Program Files\Blender Foundation\Blender\2.75\python\lib\threading.py", line 921, in _bootstrap_inner     self.run()   File "C:\Users\Davide\Desktop\Sound_Visualizer.blend\Sound_Visualizer_Circular.py", line 40, in run AttributeError: 'Context' object has no attribute 'active_object'   Can someone help me?
95092
Why does list.index throw an exception, instead of using an arbitrary value (for example, -1)? What's the idea behind this?  To me it looks cleaner to deal with special values, rather than exceptions.  EDIT: I didn't realize -1 is a potentially valid value. Nevertheless, why not something else? How about a value of None?
827
If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it,  what is the most efficient way of going through the map?  Will the ordering of elements depend on the specific map implementation that I have for the interface?
18277
Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?  I.e., I want to do this:  my_dict = {}  if (my_dict[key] != None):   my_dict[key] = 1 else:   my_dict[key] += 1   I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.
70618
So I was writing up a simple binary tree in Python and came across [...]  I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however   &gt;&gt;&gt; a [[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0] &gt;&gt;&gt; Keys(a)#With a+b [0, 1, 6, 8, 3, -4] &gt;&gt;&gt; Keys(a)#With [a,b] [8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]] &gt;&gt;&gt; Keys(a)[1]#?? [8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]     Version using a+b  def Keys(x,y=[]):     if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess     return y   version using [a,b]  def Keys(x,y=[]):     if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]     return y   So what exactly is [...]?
96022
I had the following exception thrown at me when trying to process more than one selected records via a custom button in the list view.    Class Code  global class MerchandiseInventoryClass {      webservice static void ConverttoInventory(String[] merchandise_id)    {        //Convert Merchandise collection into Inventory Collection...         Merchandise__c[] merchandise_collection = [SELECT ID,Author__c,Book_Title__c,Edition__c,Publisher__c,Total_Merchandise_QtyTotal_Qty__c,Status__c FROM Merchandise__c WHERE ID = :merchandise_id];          Inventory__c i = new Inventory__c(); //Line 1        List&lt;Inventory__c&gt; newInventory = new List&lt;Inventory__c&gt;();        for(Merchandise__c m : merchandise_collection )        {            if(m.Status__c !='Fully Converted')            {            i.Author__c = m.Author__c ;            i.Book_Title__c = m.Book_Title__c;            i.Edition__c = m.Edition__c;            i.Publisher__c = m.Publisher__c;            i.Qty_Available__c = m.Total_Merchandise_QtyTotal_Qty__c;            i.Merchandise__c = m.Id;            m.Uninventoried_Qty__c = 0;            m.Status__c = 'Fully Converted';            newInventory.add(i);            }        }        insert newInventory;        update merchandise_collection;    }  }   By moving the Line 1 to within the for loop solved the issue for me.  Thanks to this post (refer the Best Answer in that post)    What puzzles me is that WHY i have to instantiate "i" for every iteration within the loop.  Why the list collection ("newInventory") is complaining that are duplicate elements and why should it even confuse in the first place when I am performing an "insert" even ?
76838
Is there a way in Python to override a class method at instance level? For example:  class Dog:     def bark(self):         print "WOOF"  boby = Dog() boby.bark() # WOOF # METHOD OVERRIDE boby.bark() # WoOoOoF!!
110341
I have a dict where each key references an int value. What's the best way to sort the keys into a list depending on the values?
37453
I have a list of tuples like this:  [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ]   I want to iterate through this keying by the first item, so, for example, I could print something like this:  a 1 2 3 b 1 2 c 1   How would I go about doing this without keeping an item to track whether the first item is the same as I loop around the tuples? This feels rather messy (plus I have to sort the list to start with)...
93096
How can I create an  using python? I'd like to create one for each selected object and then all empties should be parented or constraint to the selected objects, meaning that the rotation and position should be copied over as well. I tried something along these lines but I can't get it to work properly: import bpy  for obj in bpy.context.selected_objects:     bpy.ops.object.empty_add()  Q: How to create an empty per object in selection?