I have created a unit class to manage units of physical quantities the user will input with their corresponding numerical values. The unit class takes a string input, and saves data in the form of three arrays containing each the physical units, their powers and a correspondence list that matches the kth element in that list to the correspondence[k]th element in the units array. In other words, the kth element represents the kth power in the powers list and the correspondence[k] element is its matching unit.
Here is the definition of that class :
class unit:
units = []
powers = []
correspondance = []
def __init__(self,input_string):
try:
assert(type(input_string)==str)
except AssertionError:
print(type(input_string))
new_string = True
new_number = True
for element in input_string :
if element.isdigit() or element == "-":
new_string = True
if new_number:
self.powers.append("")
new_number = False
self.correspondance.append(len(self.units)-1)
self.powers[-1] += element
else:
new_number = True
if new_string :
self.units.append("")
new_string = False
self.units[-1] += element
What happens is that when I define two objects p and q . q seems to have an odd behavior. Despite having the same definition as p :
p = unit("T")
print(p.units)
q = unit("T")
print(q.units)
Output
['T']
['T', 'T']
What is even strange is that when I change the order of print() functions I get yet another different output for the following code:
p = unit("T")
q = unit("T")
print(q.units)
print(p.units)
Output
['T', 'T']
['T', 'T']
The variables units, powers and correspondance are class attributes. In simple terms this means that all/any instances of the unit class will share these variables. You probably want instance variables instead. You can construct those during __init__