Why does the val_n function return an older value of self.__n? Seems to me that if obj.__n has been updated to 3, calling self.val__n should return 3 and not 2.  class myClass:     def __init__(self,n=1):         self.__n=n     def val_n(self):         return self.__n  #create an instance, __n is 2 obj=myClass(2)  #update __n to 3 obj.__n=3  #verify obj.__n has changed from 2 to 3 print(obj.__n)  #why does this still return 2? print(obj.val_n())
2890
Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: __myPrivateMethod(). How, then, can one explain this  >>> class MyClass: ...     def myPublicMethod(self): ...             print 'public method' ...     def __myPrivateMethod(self): ...             print 'this is private!!' ...  >>> obj = MyClass() >>> obj.myPublicMethod() public method >>> obj.__myPrivateMethod() Traceback (most recent call last):   File "", line 1, in  AttributeError: MyClass instance has no attribute '__myPrivateMethod' >>> dir(obj) ['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod'] >>> obj._MyClass__myPrivateMethod() this is private!!   What's the deal?!  I'll explain this a little for those who didn't quite get that.  >>> class MyClass: ...     def myPublicMethod(self): ...             print 'public method' ...     def __myPrivateMethod(self): ...             print 'this is private!!' ...  >>> obj = MyClass()   What I did there is create a class with a public method and a private method and instantiate it.  Next, I call its public method.  >>> obj.myPublicMethod() public method   Next, I try and call its private method.  >>> obj.__myPrivateMethod() Traceback (most recent call last):   File "", line 1, in  AttributeError: MyClass instance has no attribute '__myPrivateMethod'   Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running dir() on the object reveals a new magical method that python creates magically for all of your 'private' methods.  >>> dir(obj) ['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']   This new method's name is always an underscore, followed by the class name, followed by the method name.  >>> obj._MyClass__myPrivateMethod() this is private!!   So much for encapsulation, eh?  In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?
6670
I was wondering how to check whether a variable is a class (not an instance!) or not.  I've tried to use the function isinstance(object, class_or_type_or_tuple) to do this, but I don't know what type would a class will have.  For example, in the following code  class Foo: pass   isinstance(Foo, **???**) # i want to make this return True.   I tried to substitute  "class" with ???, but I realized that class is a keyword in python.
79695
I am trying to calculate a field that marks duplicates and sequentially numbers them.  I am using the code below that I found here: .  It works, but I get a duplicate starting value before it begins sequentially numbering unless I only run the field calculator on the selected values.  When I calculate after manually selecting the duplicate rows and running it on only those values, it works fine.  Here's the code:  prevFieldValue = '' counter = 0 def GetDuplicateCounter(myFieldValue):   global prevFieldValue   global counter   if myFieldValue == prevFieldValue:     counter += 1   else:     counter = 1     prevFieldValue = myFieldValue   return counter   Results running it on all roads (nothing selected):    Results running it after manually selecting the duplicated fields (not too efficient!).
105996
When I'm debugging, I often have to deal with methods that does not use an intermediate variable to store the return value :     private int myMethod_1()    {       return 12;    }     private int myMethod_2()    {       return someCall( someValue );    }   Well, in order to recreate a bug, I often have to change values on the fly. Here, I could want to see what happens when myMethode_1 return zero. Same thing for myMethod_2.  Is there a way to do that without modifying the code ? What I would like to do, it's to place a breakpoint on the return line (or on the closing bracket) and type-in a new return value.  Note : I'm using Visual Studio 2005 and Visual Studio 2008.  Thank !
85902
I found the following behavior at least weird:  def errors():     try:         ErrorErrorError     finally:         return 10  print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined   The exception disappears when you use return inside a finally clause. Is that a bug? Is that documented anywhere?  But the real question (and the answer I will mark as correct) is: What is the python developers' reason to allow that odd behavior?
10585
Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like  [2,2,2] - [1,1,1] = [1,1,1]   Should I use tuples?  If none of them defines these operands on these types, can I define it instead?  If not, should I create a new vector3 class?
8925
Suppose I have a python object x and a string s, how do I set the attribute s on x? So:  &gt;&gt;&gt; x = SomeObject() &gt;&gt;&gt; attr = 'myAttr' &gt;&gt;&gt; # magic goes here &gt;&gt;&gt; x.myAttr 'magic'   What's the magic? The goal of this, incidentally, is to cache calls to x.__getattr__().
92805
I have a class A and another class that inherits from it, B. I am overriding a function that accepts an object of type A as a parameter, so I have to accept an A. However, I later call functions that only B has, so I want to return false and not proceed if the object passed is not of type B.  What is the best way to find out which type the object passed to my function is?
2266
In follow up to , it appears that some numbers cannot be represented by floating point at all, and instead are approximated.  How are floating point numbers stored?  Is there a common standard for the different sizes?  What kind of gotchas do I need to watch out for if I use floating point?  Are they cross-language compatible (ie, what conversions do I need to deal with to send a floating point number from a python program to a C program over TCP/IP)?
5812
Why does the  exist in modern languages such as C# and Java? Is it purely a self documenting code feature, or does it serve any actual purpose?  For instance the following example:  Class1 obj = new Class1();  Class1 foo() {     return new Class1(); }   Is as easy to read as the more Pythonesque way of writing it:  Class1 obj = Class1();  Class1 foo() {     return Class1(); }   EDIT:  hit the nail on the head with the clarification of the question: Why did they choose this syntax?
20628
I would like to clarify the differences between by value and by reference.  I drew a picture     So, for passing by value,  a copy of an identical object is created with a different reference, and the local variable is assigned the new reference, so to point to the new copy  How to understand the words: " If the function modifies that value, the modifications appear also within the scope of the calling function for both passing by value and by reference "  Thanks!
78279
I'm sure there's a simpler way of doing this that's just not occurring to me.  I'm calling a bunch of methods that return a list.  The list may be empty.  If the list is non-empty, I want to return the first item; otherwise, I want to return None.  This code works:  my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None   It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it.  Is there?  Edit:  The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:  x = get_first_list() if x:     # do something with x[0]     # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y:     # do something with y[0]     # inevitably forget the [0] part AGAIN, and have another bug to fix   What I'd like to be doing can certainly be accomplished with a function (and probably will be):  def first_item(list_or_none):     if list_or_none: return list_or_none[0]  x = first_item(get_first_list()) if x:     # do something with x y = first_item(get_second_list()) if y:     # do something with y   I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick.  But seeing these answers, it seems like a function is the simple solution.
13706
The canonical way to return multiple values in languages that support it is often . Option: Using a tuple Consider this trivial example: def f(x):   y0 = x + 1   y1 = x * 3   y2 = y0 ** y3   return (y0, y1, y2)  However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them. Option: Using a dictionary The next logical step seems to be to introduce some sort of 'record notation'. In Python, the obvious way to do this is by means of a dict. Consider the following: def g(x):   y0 = x + 1   y1 = x * 3   y2 = y0 ** y3   return {'y0': y0, 'y1': y1 ,'y2': y2}  (Just to be clear, y0, y1, and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers.) Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, result['y0']  Option: Using a class However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes: class ReturnValue:   def __init__(self, y0, y1, y2):      self.y0 = y0      self.y1 = y1      self.y2 = y2  def g(x):   y0 = x + 1   y1 = x * 3   y2 = y0 ** y3   return ReturnValue(y0, y1, y2)  In Python the previous two are perhaps very similar in terms of plumbing - after all { y0, y1, y2 } just end up being entries in the internal __dict__ of the ReturnValue. There is one additional feature provided by Python though for tiny objects, the __slots__ attribute. The class could be expressed as: class ReturnValue(object):   __slots__ = [&quot;y0&quot;, &quot;y1&quot;, &quot;y2&quot;]   def __init__(self, y0, y1, y2):      self.y0 = y0      self.y1 = y1      self.y2 = y2  From the :  The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.  Option: Using a  (Python 3.7+) Using Python 3.7's new dataclasses, return a class with automatically added special methods, typing and other useful tools: @dataclass class Returnvalue:     y0: int     y1: float     y3: int  def total_cost(x):     y0 = x + 1     y1 = x * 3     y2 = y0 ** y3     return ReturnValue(y0, y1, y2)  Option: Using a list Another suggestion which I'd overlooked comes from Bill the Lizard: def h(x):   result = [x + 1]   result.append(x * 3)   result.append(y0 ** y3)   return result  This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are , whereas tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types. Question After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?
33578
I'm learning the Python programming language and I've came across something I don't fully understand.   In a method like:  def method(self, blah):     def __init__(?):         ....     ....   What does self do?  What is it meant to be?  Is it mandatory?  What does the __init__ method do?  Why is it necessary? (etc.)  I think they might be OOP constructs, but I don't know very much.
6639
What's the difference between:  class Child(SomeBaseClass):     def __init__(self):         super(Child, self).__init__()   and:  class Child(SomeBaseClass):     def __init__(self):         SomeBaseClass.__init__(self)   I've seen super being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.
106335
What does the following mean?  Class.Function(variable := 1 + 1)   What is this operator called, and what does it do?
7441
Was there any reason why the designers of Java felt that local variables should not be given a default value? Seriously, if instance variables can be given a default value, then why can't we do the same for local variables?  And it also leads to problems as explained in :     Well this rule is most frustrating when trying to close a resource in a finally block. If I instantiate the resource inside a try, but try to close it within the finally, I get this error. If I move the instantiation outside the try, I get another error stating that a it must be within a try.      Very frustrating.