I recently conquered this pass by ref thing. This is how I did it. Python 2.4.3 (#1, Apr 3 2006, 14:02:53) [GCC 3.4.6] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def f1(v): ... v="asdf" ... >>> def f2(v): ... v=["asdf"] ... >>> def f3(v): ... v.append("asdf") ... >>> a="fdsa" >>> b=["fdsa"] >>> f1(a) >>> a 'fdsa' >>> f1(b) >>> b ['fdsa'] >>> f2(a) >>> a 'fdsa' >>> f2(b) >>> b ['fdsa'] >>> f3(a) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in f3 AttributeError: 'str' object has no attribute 'append' >>> f3(b) >>> b ['fdsa', 'asdf'] >>> if you only want one value in there, you can pop off the first value and then append. def f4(v): _old=v.pop() v.append("asdf")
you can then also turn it back into a string by doing this: b[0] I was very glad to have learned this way to do by ref. Thanks. On Wed, Dec 31, 2008 at 11:32 PM, Aaron Brady <castiro...@gmail.com> wrote: > On Dec 31, 5:30 am, iu2 <isra...@elbit.co.il> wrote: > > Hi, > > > > Is it possible somehow to change a varible by passing it to a > > function? > > > > I tried this: > > > > def change_var(dict0, varname, val): > > dict0[varname] = val > > > > def test(): > > a = 100 > > change_var(locals(), 'a', 3) > > print a > > > > But test() didn't work, the value a remains 100. > > > > I have several variables initialized to None. > > I need to convert each one of them an object only if it is None. > > something like: > > > > if not var1: var1 = MyObject() > > > > I want this to be a function, that is: > > > > def create_obj(var): > > if not var: var = MyObj() > > # set properties of var > > > > Now, I know I can achieve this by functional programming, > > > > def create_obj(var): > > if not var: > > x = MyObj() > > # set properties of x > > return x > > return var > > > > and then > > > > var = creaet_obj(var) > > > > Is there another way? > > > > Thanks > > A practical way is to use a container. Some people use lists; I like > an object. > > thingref= Ref( thing ) > f( thingref ) > print thingref() #or thingref.get() or w'ver. > > Then 'f' can assign like this: > > def f( aref ): > # blah blah > aref( newthing ) #or aref.set( newthing ) > > But the short answer is no. A function receives the contents of a > variable, not a variable. > -- > http://mail.python.org/mailman/listinfo/python-list > -- А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
-- http://mail.python.org/mailman/listinfo/python-list