CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Python (http://www.codingforums.com/forumdisplay.php?f=46)
-   -   Looping through an Object's members and changing its values (http://www.codingforums.com/showthread.php?t=209821)

Apothem 11-21-2010 09:31 AM

Looping through an Object's members and changing its values
 
Say I have:
PHP Code:

obj.one "Hello, World!"
obj.two "Goodbye, World!"
obj.three "Foo"
obj.four "Bar" 

1. How do I loop through it and change "o" to "a"?
2. Make the changed value permanent (i.e. I changed it by reference)
In PHP you, it's basically this:
PHP Code:

$v = (object)array('one' => "foooo"'two' => "bo");
for( 
$v => &$val ) {
$val str_replace('o'$val);



Samhain13 11-21-2010 07:47 PM

You can use the object's internal dictionary (assuming "obj" is an instance of some object):

Code:

for o in obj.__dict__:
    obj.__dict__[o] = "some new value"

If you have a source, like another dictionary that contains the same keys as the object's properties:

Code:

sauce = {"one": "some", "two": "value", "three": "here" }
for k, v in sauce.items():
    # Do nothing if k is not a property of obj.
    if obj.__dict__.get(k):
        obj.__dict__[k] = v

More to address your problem:
Code:

for key, value in obj.__dict__.items():
    obj.__dict__[k] = value.replace("o", "replacement text")



All times are GMT +1. The time now is 12:53 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.