[Edu-sig] teaching Python
John Posner
jjposner at optimum.net
Sat Apr 24 01:15:59 CEST 2010
Bill Punch<punch at cse.msu.edu> said:
<snip>
> Default mutables are very confusing indeed. The recommended procedure is
> to assign the default to be None, then check for that value in the
> function and do the assignment there, such as:
>
> def myFun(myList=None):
> if myList == None:
> myList = []
> ...
>
+1. This issue comes up on python-list about once a month.
> So is the example of replicating a mutable as Mark showed. To round out
> the top three, which are the ones that get even my best students, look
> at the below:
>
> myVar = 27
>
> def myFun ():
> print myVar
> myVar += 1
> return myVar
>
> print myFun
>
> What happens when you run this?
>
Oops, you meant *print myFun()* there. On the bright side, an error
occurs, warning you of your errant ways:
UnboundLocalError: local variable 'myVar' referenced before assignment
Perhaps more gotcha-esque is this similar situation, in which no error
occurs:
#----------------------------------
class MyClass:
var = 101 # class attribute
def try_to_modify_class_attribute(self):
self.var += 13
def show(self):
print self.var
obj1 = MyClass()
obj2 = MyClass()
obj1.try_to_modify_class_attribute()
obj1.show() # output: 114
obj2.show() # output: 101
#----------------------------------
-John
More information about the Edu-sig
mailing list