Reputation: 80
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".
Upvotes: 1
Views: 49
Reputation: 170
Using A Dictionary
Like @deceze said, using a dict mapping the number to a tuple is one way. What you could do is set up the tuple like so: ("Name", "unit", "tag - optional")
. Then, you could take the size of the tuple to see if it has a tag or not. So, the dict would look like:
class variable():
def __init__(self, number):
self.no = number
self.longname = "Long variable name"
self.name = "Variable"
self.tag = "tag"
self.unit = "unit"
self.map = {1: ('Second','[s]'), 2: ('Metre', '[m]'),
3: ('Kilogram', '[kg]', 'kg'), 4: ('Ampere', '[A]', 'Amp')}
def get_varname(self):
selfTuple = self.map[self.no]
self.name = selfTuple[0]
self.unit = selfTuple[1]
if (len(selfTuple)==3):
self.tag = selfTuple[2]
Using Match Case in 3.10
In Python 3.10, you can use a special statement called match case. It is similar to the switch statement in Java.
class variable():
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):
match self.no:
case 1:
self.name = 'Second'
self.unit = '[s]'
case 2:
self.name = 'Metre'
self.unit = '[m]'
case 3:
self.name = 'Kilogram'
self.tag = 'kg'
self.unit = '[kg]'
case 4:
self.name = 'Ampere'
self.tag = 'Amp'
self.unit = '[A]'
Upvotes: 1