class Temperature():
def convertF(self,c):
return c*1.8 32
def convertC(self,f):
return (f-32)*(5/9)
c=float(input())
f=float(input())
n_temp=Temperature(c)
n_temp=Temperature(f)
print(n_temp.convertF)
print(n_temp.convertC)
I've creating a class Temperature
, then I created 2 methods one for converting Celsius to Fahrenheit and another for converting the latter to former.
Now I want to take the values of Celsius and Fahrenheit from user but I'm getting the error :
Temperature() takes no arguments.
Can someone tell me what I'm doing wrong?
CodePudding user response:
Temperature (the class) doesn't take any arguments; each of its methods does take an argument.
CodePudding user response:
If you want to use Temperature(<value>)
, you need a constructor. Once you have a constructor, your other methods dont need parameters
class Temperature():
def __init__(self, temp):
self.temp = temp
def convertF(self):
return self.temp * 1.8 32
def convertC(self):
return (self.temp-32)*(5/9)
n_temp=Temperature(float(input()))
print(n_temp.convertC()) # you need to call the function
Or you can use static methods if you don't want to use a constructor (since the constructor itself doesn't know if the input is in Celcius, Farenheit, or Kelvin), but then you would need to remove the argument from the class initialization, and pass it to the functions
# call a static method
print(Temperature.convertC(0)) # 32