&gt;&gt;&gt; class A: ...     def foo(self): ...             print(self) ... &gt;&gt;&gt; &gt;&gt;&gt; a = A() &gt;&gt;&gt; a.foo() &lt;__main__.A instance at 0x7f4399136cb0&gt; &gt;&gt;&gt; def foo(self): ...     print(self) ... &gt;&gt;&gt; a.foo = foo &gt;&gt;&gt; a.foo() Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: foo() takes exactly 1 argument (0 given)   I am trying to understand monkey-patching in Python. Please illustrate the reason for the error and how to fix it.
6666
I've read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python.   I understand that it's not always good to do so. But how might one do this?
10090
I got the following class :  class ConstraintFailureSet(dict, Exception) :     """         Container for constraint failures. It act as a constraint failure itself         but can contain other constraint failures that can be accessed with a dict syntax.     """      def __init__(self, **failures) :         dict.__init__(self, failures)         Exception.__init__(self)  print isinstance(ConstraintFailureSet(), Exception) True raise ConstraintFailureSet() TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet   What the heck ?  And the worst is that I can't try super() since Exception are old based class...  EDIT : And, yes, I've tried to switch the order of inheritance / init.  EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...
89256
I want to assign a class attribute via a string object - but how?  Example:  class test(object):   pass  a = test() test.value = 5 a.value # -&gt; 5 test.__dict__['value'] # -&gt; 5  # BUT: attr_name = 'next_value'  test.__dict__[attr_name] = 10 # -&gt; 'dictproxy' object does not support item assignment
87845
I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called  that purports to do exactly that:  import timeit  def foo():     # ... contains code I want to time ...  def dotime():     t = timeit.Timer("foo()")     time = t.timeit(1)     print "took %fs\n" % (time,)  dotime()   However, this produces an error:  Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt;   File "&lt;stdin&gt;", line 3, in dotime   File "/usr/local/lib/python2.6/timeit.py", line 193, in timeit     timing = self.inner(it, self.timer)   File "&lt;timeit-src&gt;", line 6, in inner NameError: global name 'foo' is not defined   I'm still new to Python and I don't fully understand all the scoping issues it has, but I don't know why this snippet doesn't work. Any thoughts?
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?
31376
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?  Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of  import foo from bar.baz import quux  def myFunction():     foo.this.that(quux)   I move all my imports into the function where they're actually used., like this:  def myFunction():     import foo     from bar.baz import quux      foo.this.that(quux)   This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.  Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.
18919
I am typing to get a sale amount (by input) to be multiplied by a defined sales tax (0.08) and then have it print the total amount (sales tax times sale amount).  I run into this error. Anyone know what could be wrong or have any suggestions?   salesAmount = raw_input (["Insert sale amount here \n"]) ['Insert sale amount here \n']20.99 &gt;&gt;&gt; salesTax = 0.08 &gt;&gt;&gt; totalAmount = salesAmount * salesTax  Traceback (most recent call last):   File "&lt;pyshell#57&gt;", line 1, in &lt;module&gt;     totalAmount = salesAmount * salesTax TypeError: can't multiply sequence by non-int of type 'float'
10472
\documentclass{article} \usepackage{xparse}  \DeclareDocumentCommand\TestA{&gt;{\SplitArgument{1}{:}}m}{%   \Example #1 }  \ExplSyntaxOn \DeclareDocumentCommand\TestB{&gt;{\SplitArgument{1}{:}}m}{   \Example #1 } \ExplSyntaxOff   \DeclareDocumentCommand\Example{mm}{%   \begin{enumerate}   \item #1   \item #2   \end{enumerate} }  \begin{document} \TestA{one : two} \TestB{one : two} \end{document}
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!!
72908
I am trying to figure out this:  c = 1 def f(n):     print c + n  def g(n):     c = c + n  f(1) # =&gt; 2 g(1) # =&gt; UnboundLocalError: local variable 'c' referenced before assignment   Thanks!
18032
I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo.  However, I'm looking through the wxPython in Action book and notice that "self" isn't used all the time. For example:   import wx  class TextFrame(wx.Frame):     def __init__(self):         wx.Frame.__init__(self, None, -1, 'Text Entry Example',             size=(300, 100))         panel = wx.Panel(self, -1)         basicLabel = wx.StaticText(panel, -1, "Basic Control:")         basicText = wx.TextCtrl(panel, -1, "I've entered some text!",             size=(175, -1))         basicText.SetInsertionPoint(0)         pwdLabel = wx.StaticText(panel, -1, "Password:")         pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1),             style=wx.TE_PASSWORD)         sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)         sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText])         panel.SetSizer(sizer)   The one below does use "self".  import wx class ButtonFrame(wx.Frame):     def __init__(self):         wx.Frame.__init__(self, None, -1, 'Button Example',             size=(300, 100))         panel = wx.Panel(self, -1)         self.button = wx.Button(panel, -1, "Hello", pos=(50, 20))         self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)         self.button.SetDefault()     def OnClick(self, event):         self.button.SetLabel("Clicked")   If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb?
24071
I'm trying to understand Python's approach to variable scope. In this example, why is f() able to alter the value of x, as perceived within main(), but not the value of n?  def f(n, x):     n = 2     x.append(4)     print('In f():', n, x)  def main():     n = 1     x = [0,1,2,3]     print('Before:', n, x)     f(n, x)     print('After: ', n, x)  main()   Output:  Before: 1 [0, 1, 2, 3] In f(): 2 [0, 1, 2, 3, 4] After:  1 [0, 1, 2, 3, 4]
4188
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:  flist = []  for i in xrange(3):     def func(x): return x * i     flist.append(func)  for f in flist:     print f(2)   Note that this example mindfully avoids lambda. It prints "4 4 4", which is surprising. I'd expect "0 2 4".   This equivalent Perl code does it right:  my @flist = ();  foreach my $i (0 .. 2) {     push(@flist, sub {$i * $_[0]}); }  foreach my $f (@flist) {     print $f-&gt;(2), "\n"; }   "0 2 4" is printed.  Can you please explain the difference ?    Update:   The problem is not with i being global. This displays the same behavior:  flist = []  def outer():     for i in xrange(3):         def inner(x): return x * i         flist.append(inner)  outer() #~ print i   # commented because it causes an error  for f in flist:     print f(2)   As the commented line shows, i is unknown at that point. Still, it prints "4 4 4".
3866
Is it possible to have static class variables or methods in Python? What syntax is required to do this?
60133
I'm trying to run the remove_doubles edit command on multiple selected objects. This is kinda what I got so far...  import bpy   class remDoubles(bpy.types.Operator):     """Remove Doubles on multiple objects"""     bl_label = "Remove Multiple Doubles"     bl_idname = "object.remove_doubles_multi"     bl_options = {'REGISTER', 'UNDO'}      @classmethod     def poll(cls, context):         return len(context.selected_objects) &gt; 0      def execute(self, context):          scene = bpy.context.scene         sel = context.selected_objects          for obj in sel:             scene.objects.active = obj              #do something here             print(obj.name)             bpy.ops.mesh.remove_doubles()          return {"FINISHED"}  myobject = remDoubles()  myobject.execute()   My knowledge about classes isn't too great, please help.  My code needs some work, it just errors out giving a  'TypeError: bpy_struct.new(type): expected a single argument'  But what i intend doing is run through each object applying the remove doubles command for each.
43791
I wasn't following Meta Stack Overflow too closely so maybe something was changed that I'm not aware of. But each time I paste a snippet from a Python console I'm getting wrong formatting. What I'm doing wrong? It seems that &gt;&gt;&gt; is confusing for Stack Overflow. I've tried to escape it with backslashes, and it was working fine in preview but doesn't work after the question is rendered.  I was able to observe that problem on: recent Chrome (Windows, Mac), Safari 4 (Mac).  Here is  I wasn't able to make right.  Funny, I think the snippets are rendered just fine on Meta Stack Overflow. Here is one:  &gt;&gt;&gt; def throw(): raise Exception()  ...  &gt;&gt;&gt; a=1 &gt;&gt;&gt; a=throw() Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt;   File "&lt;stdin&gt;", line 1, in throw Exception &gt;&gt;&gt; a 1
106335
What does the following mean?  Class.Function(variable := 1 + 1)   What is this operator called, and what does it do?