0

Here is a class

Class A:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def set_value(self,"attribut_String",value):   # passing a attribute in String
        if "attribut_String" = "AAAA":
            self.cal_function("a",value) 
        else "attribut_String" = "BBBB":
            self.cal_function("b",value) 

    def cal_function(self,att,value):
        self.att = value       # process the passing string as attribute object

Now , i'm try to a result like this :

input:rlt = A(a = 1, b = 2)
input:rlt.a
output: 1
input:rlt.set_value("a",3)
input:rlt.a
output:4

May it seems unnecessary because I simplified the scenario . I have to code in this way

2
  • 3
    have a look at getattr and setattr Commented Nov 14, 2012 at 9:33
  • 1
    What not just use rlt.a = 3? Commented Nov 14, 2012 at 9:36

1 Answer 1

3

You can use a control flow inside your set_value function:

def set_value(self, member, value):
    if member == "a":
        self.a = value
    elif member == "b":
        self.b = value

If you don't mind dropping the set_value function, you can use the setattr function:

setattr(myobject, "a", value)

or even

def set_value(self, member, value):
    setattr(self, member, value)

You can also use a dictionary:

def set_value(self, member, value):
    members = {
        "a" : self.a,
        "b" : self.b
    }
    members[member] = value
Sign up to request clarification or add additional context in comments.

2 Comments

what do you do with members in the last step?
hi, Alestanis , that's really classic explanation . but sorry , I didn't make myself clear enough..could you pls check the updated question ?Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.