hi I've recently started working with classes in python and there is a code which I must use class for converting temperature scales . for example you choose two scales and give the temp in the first scale and the temp in the second scale will be shown in the output.one way is to use if condition , for example I can get an input from the user and after checking the conditions call the desired method:
class temp_convertor:
def c_f(c):
f = 1.8*(c) 32
return f
def f_c(f):
c = (f-32)*(5/9)
return c
def c_k(c):
k = c 273.15
return k
def k_c(k):
c = k-273.15
return c
def c_r(c):
r = temp_convertor.c_f(c) 459.67
return r
def r_c(r):
c = temp_convertor.f_c(r-459.67 )
return c
def k_r(k):
r = temp_convertor.c_r(temp_convertor.k_c(k))
return r
def r_k(r):
k = temp_convertor.c_k(temp_convertor.r_c(r))
return k
a = input("scale1,scale2: ")
if a == "f,c":
temp_convertor.f_c(float(input("temp? ")))
elif a == "c,f":
temp_convertor.c_f(float(input("temp? ")))
# and for every convertor I should continue checking conditions :(
but I've used global()[name] for calling functions before for example:
def apple(a):
print(2*a)
globals()[input("type apple if you want to double your number: ")](int(input("number: ")))
and the output is something like this:
type apple if you want to double your number: apple
number: 5
10
but I can't use that here:
class temp_convertor:
def c_f(c):
f = 1.8*(c) 32
return f
def f_c(f):
c = (f-32)*(5/9)
return c
def c_k(c):
k = c 273.15
return k
def k_c(k):
c = k-273.15
return c
def c_r(c):
r = temp_convertor.c_f(c) 459.67
return r
def r_c(r):
c = temp_convertor.f_c(r-459.67 )
return c
def k_r(k):
r = temp_convertor.c_r(temp_convertor.k_c(k))
return r
def r_k(r):
k = temp_convertor.c_k(temp_convertor.r_c(r))
return k
print(temp_convertor.globals()[input("scale1_scale2")](float(input("temp? "))))
and the error is : AttributeError: type object 'temp_convertor' has no attribute 'globals' I want to know if the second solution is somehow possible and if not is there any shorter solution ? Thanks for reading this!
CodePudding user response:
use
getattr(temp_convertor, input('scale1_scale2: '))(float(input('temp? ')))