lundi 26 avril 2021

Elegant way to set class variables without elseif

I am new to python, so I am sorry if there is an obvious solution. I am working on someones code which looks like this (with a total of 80 entries):

class variable():
number = ""

def __init__(self, number):
    self.no = number
    self.longname = "Long variable name"
    self.name = "Variable"
    self.tag = "tag"
    self.unit = "unit"

def get_varname(self):

    if self.no == 1:
        self.name = 'Second'
        self.unit = '[s]'
    elif self.no == 2:
        self.name = 'Metre'
        self.unit = '[m]'
    elif self.no == 3:
        self.name = 'Kilogram'
        self.tag = 'kg'
        self.unit = '[kg]'
    elif self.no == 4:
        self.name = 'Ampere'
        self.tag = 'Amp'
        self.unit = '[A]'

Is there any elegant way to rewrite this? I guess one way to do it is with a dictionary, but I am not sure if this makes the code easier. Also only some entries contain "tag".

Aucun commentaire:

Enregistrer un commentaire