Search This Blog

Friday, April 26, 2013

How to use mutable and immutable objects as default values in Python

Python as a dynamic language allow us to define mutable and immutable objects and variables. There is a significant difference now what a function or class can do with its positional arguments depending if the arguments are immutable or not.

The example code below are taken from this blog post: Gotcha — Mutable default arguments. Do you know what is going to be printed on stdout and why (he explanation and results can be found in the link above)?
 
def foobar(arg_string="abc", arg_list = []): 
    print arg_string, arg_list 
    arg_string = arg_string + "xyz"
    arg_list.append("F")
 
for i in range(4): 
    foobar()

# (1) define a class for company employees 
class Employee:
    def __init__ (self, arg_name, arg_dependents=[]): 
        # an employee has two attributes: a name, and a list of his dependents 
        self.name = arg_name 
        self.dependents = arg_dependents
     
    def addDependent(self, arg_name): 
        # an employee can add a dependent by getting married or having a baby 
        self.dependents.append(arg_name)
     
    def show(self): 
        print
        print "My name is.......: ", self.name 
        print "My dependents are: ", str(self.dependents)
#--------------------------------------------------- 
#   main routine -- hire employees for the company 
#---------------------------------------------------
 
# (2) hire a married employee, with dependents 
joe = Employee("Joe Smith", ["Sarah Smith", "Suzy Smith"])
 
# (3) hire a couple of unmarried employess, without dependents 
mike = Employee("Michael Nesmith") 
barb = Employee("Barbara Bush")
 
# (4) mike gets married and acquires a dependent 
mike.addDependent("Nancy Nesmith")
 
# (5) now have our employees tell us about themselves 
joe.show() 
mike.show() 
barb.show()

No comments:

Post a Comment