faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 4 people (25%) answered Yes
Recently 0 of 3 people (0%) answered Yes

Entry

Assign a value to another variable through a method

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 350, Les Schaffer


"""
Packages: oop;miscellaneous
"""

"""
From:           	Les Schaffer <godzilla@netmeg.net>
Subject:        	Re: assign a value to another variable throught a method
Date sent:      	30 Jan 1999 10:39:51 -0500
To:             	python-list@cwi.nl

>>>>> ">" == lstep  <lstep@mail.dotcom.fr> writes:

    >> I wanted another_name to be 'mapped' on foo or bar (not needing >>
    to do a if another_name == 'foo': self.foo = value if >> another_name
    == 'bar': self.bar = value etc..
"""
#========== setattr.py

#!/usr/bin/python

class a_class:
    def __init(self):
        self.foo = []       #  <--- you forgot your self
        self.bar = []       #      "

    def assign_it(self, another_name, value):
        setattr(self,another_name, value)

    def protected_assign_it(self, another_name, value):
        if hasattr(self, another_name): setattr(self, another_name, value)


a = a_class()
a.assign_it('foo', "hello world")
print a.foo

a.assign_it('baz', 'farewell world')
print a.baz

a.protected_assign_it('biz', 'goodnite ophelia')
print a.biz

# example output
#==============
"""
(gustav)~/: python setattr.py
hello world
farewell world
Traceback (innermost last):
  File "setattr.py", line 22, in ?
    print a.biz
AttributeError: biz
"""