Go Back   CodingForums.com > :: Server side development > Other server side languages/ issues > Python

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-21-2010, 09:31 AM   PM User | #1
Apothem
Regular Coder

 
Apothem's Avatar
 
Join Date: Mar 2008
Posts: 380
Thanks: 36
Thanked 25 Times in 25 Posts
Apothem is an unknown quantity at this point
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);


Last edited by Apothem; 11-21-2010 at 09:33 AM..
Apothem is offline   Reply With Quote
Old 11-21-2010, 07:47 PM   PM User | #2
Samhain13
Regular Coder

 
Samhain13's Avatar
 
Join Date: Aug 2008
Location: Pilipinas
Posts: 165
Thanks: 4
Thanked 18 Times in 18 Posts
Samhain13 is on a distinguished road
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")
__________________
I am a Man of Truth. I am a Free Human Person. I am a Peacemaker.
** Independent Multimedia Artist in Pasig **

Last edited by Samhain13; 11-21-2010 at 07:51 PM..
Samhain13 is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 08:39 AM.


Advertisement
Log in to turn off these ads.