0

I want to make this kind of code shorter

if something == "x":
  object.x += 10

if something == "y":
  object.y += 10

if something == "z":
  object.z += 10

To make it something like this below

object.contentof(something) += 10

And this is my original code. It's kind simple but it starts to be a mess when its in many places and I want to add new currency to be viable

if trans.currency== "CNY":
    if trans.sender_id.cny-trans.value >= 0:
        sender.cny  -= trans.value
        reciver.cny += trans.value
elif trans.currency== "RUB":
    if trans.sender_id.rub-trans.value >= 0:
        sender.rub  -= trans.value
        reciver.rub += trans.value
elif trans.currency== "LIR":
    if trans.sender_id.rub-trans.value >= 0:
        sender.lir  -= trans.value
        reciver.lir += trans.value                           

  • where is the question? – Hasan Aga Apr 08 '22 at 15:26
  • 1
    While it is possible to get a instance variable's value based on a string, this is often the wrong solution. Have you considered using a dictionary instead of a class? – Code-Apprentice Apr 08 '22 at 15:28
  • "It's kind simple but it starts to be a mess when its in many places" Then you should create a function with the code and just call that function instead of repeating the same code in multiple places. In fact, you might want to create a currency class. Then the common code becomes a method of the class. – Code-Apprentice Apr 08 '22 at 15:29
  • @PranavHosangadi Your advice kind of helps. I'll try to implement it in my program. I don't think I can change the desing of my program becouse. I've got the user object witch has variables for different types of currencies and I can't imagine how it could look differently. The same code isn't used in lot of places but similar kind of code. – Eg-Nickname Apr 08 '22 at 15:44

2 Answers2

0

There is no way to get a reference at the attribute, but you can get its content:

setattr(object, something, getattr(object, something) + 10)

However, even though this works, I agree with the comments saying this should probably be solved with a better program design.

jthulhu
  • 7,223
  • 2
  • 16
  • 33
0

You are better off first doing something like

class Obj: 
    def __init__(self, x = None, y = None, z = None):
        self.d = {'x': x, 'y': y, 'z': z}
        # other stuff
    # other stuff 

If you don't want to specify x, y, z at instance creation time you do not need to.

After some setup like the above, you can do something like

o = Obj(3, 5, 8)

o.d = dict(map(lambda i: (i[0], i[1] + 10), o.d.iteritems()))
print(o.d)

o.d = {i: j + 10 for i, j in o.d.items()}
print(o.d)

Output

{'y': 15, 'x': 13, 'z': 18}
{'y': 25, 'x': 23, 'z': 28}
OTheDev
  • 2,916
  • 2
  • 4
  • 20