Home > Mobile >  Assign dict values as arguments in Python
Assign dict values as arguments in Python

Time:01-30

I'm using a class

class Variable():
    def __init__(self, value, ratio):
    self.value = value
    self.ratio = {'A': 0.0, 'B': 0.0, 'C': 0.0}

and I would like to assign a value and a ratio (to one of A, B or C) when initializing, i.e.

> var1 = Variable(3.2, 'A'=100.0)

so that the outcome would be

> var1.value
3.2
> var1.ratio
{'A': 100.0, 'B': 0.0, 'C': 0.0}

Is this possible with a function argument like this, or should I use some other method?

CodePudding user response:

define default value for each parameter and use them directly into dict:

class Variable():
    def __init__(self, value, A=0.0, B=0.0, C=0.0):
        self.value = value
        self.ratio = {'A': A, 'B': B, 'C': C}

and you are ready to go

var1 = Variable(3.2, A=100.0)
var1.ratio
{'A': 100.0, 'B': 0.0, 'C': 0.0}

CodePudding user response:

You can do something like that:

class Variable:
    def __init__(self, value, ratio):
        self.value = value
        self.ratio = {'A' : 0.0, 'B' : 0.0, 'C' : 0.0}
        self.ratio.update(ratio)

var1 = Variable(3.2, {'A' : 100.0})
print(var1.value) # 3.2
print(var1.ratio) # {'A': 100.0, 'B': 0.0, 'C': 0.0}
  •  Tags:  
  • Related