
Untitled
By: a guest on
May 25th, 2012 | syntax:
None | size: 1.71 KB | hits: 11 | expires: Never
What is the most preferred way to pass object attributes to a function in Python?
class my_file_obj:
def __init__(self,filename):
self.filename = filename
self.owner = None
self.file_type = None
self.fileflag = 0
self.md5 = None
some_function(file_obj1)
# with this call the file_obj1 object reference is sent to some_function()
some_function(file_obj1)
# with this call there is no pass by reference. If filename is a
# string it is copied to some_function
some_function(file_obj1.filename)
# same as before, but here you are allocating a new var and copying the content
# to some_function
the_filename = file_obj1.filename
some_function(the_filename)
def some_function(file_thingy):
with open(file_thingy.filename, 'w') as f:
f.write("Icky Icky Icky Patang NeeeeWom!")
def do_duck_things(a_duck):
print(a_duck.appearance)
a_duck.waddle()
a_duck.quack()
print("It must be a duck!")
class Duck:
def __init__(self):
self.appearance = "White, like the AFLAC duck"
def quack(self):
print("Quaaaaaack!")
def waddle(self):
print("The duck waddles.")
class UglyDuckling:
def __init__(self):
self.appearance = "Suspiciously like a baby goose"
def waddle(self):
print("The ugly duckling waddles a bit like a duck.")
def quack(self):
print("Hoooonk!")
class Human:
def __init__(self):
self.appearance = "Looks like a human in a duck costume"
def waddle(self):
print("Surprisingly, he waddles quite like a duck.")
def quack(self):
print("<A sound quite like Donald Duck would make>")
def openFile(obj):
return open(str(obj), 'rU')