Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 25th, 2012  |  syntax: None  |  size: 1.71 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. What is the most preferred way to pass object attributes to a function in Python?
  2. class my_file_obj:
  3.     def __init__(self,filename):
  4.         self.filename = filename
  5.         self.owner = None
  6.         self.file_type = None
  7.         self.fileflag = 0
  8.         self.md5 = None
  9.        
  10. some_function(file_obj1)
  11.        
  12. # with this call the file_obj1 object reference is sent to some_function()
  13. some_function(file_obj1)
  14.  
  15. # with this call there is no pass by reference. If filename is a
  16. # string it is copied to some_function
  17. some_function(file_obj1.filename)
  18.  
  19. # same as before, but here you are allocating a new var and copying the content
  20. # to some_function
  21. the_filename = file_obj1.filename
  22. some_function(the_filename)
  23.        
  24. def some_function(file_thingy):
  25.    with open(file_thingy.filename, 'w') as f:
  26.        f.write("Icky Icky Icky Patang NeeeeWom!")
  27.        
  28. def do_duck_things(a_duck):
  29.     print(a_duck.appearance)
  30.     a_duck.waddle()
  31.     a_duck.quack()
  32.     print("It must be a duck!")
  33.        
  34. class Duck:
  35.     def __init__(self):
  36.         self.appearance = "White, like the AFLAC duck"
  37.  
  38.     def quack(self):
  39.         print("Quaaaaaack!")
  40.  
  41.     def waddle(self):
  42.         print("The duck waddles.")
  43.        
  44. class UglyDuckling:
  45.     def __init__(self):
  46.         self.appearance = "Suspiciously like a baby goose"
  47.  
  48.     def waddle(self):
  49.         print("The ugly duckling waddles a bit like a duck.")
  50.  
  51.     def quack(self):
  52.         print("Hoooonk!")
  53.  
  54. class Human:
  55.     def __init__(self):
  56.         self.appearance = "Looks like a human in a duck costume"
  57.  
  58.     def waddle(self):
  59.         print("Surprisingly, he waddles quite like a duck.")
  60.  
  61.     def quack(self):
  62.         print("<A sound quite like Donald Duck would make>")
  63.        
  64. def openFile(obj):
  65.     return open(str(obj), 'rU')