Robin Sage
Robin Sage

Reputation: 959

Need help calling a function from another class in python

I wrote a simple unit converter program. In the main() class, I have the basic program asking the user to choose which converter to use. Then I wrote a specific class for each converter. What I would like to do is to import each converter method into main. Truth be told, I'm not sure if I even need main(). Anyway, all classes work, I just don't know how to import the methods into their appropriate placeholders. I hope this makes sense.

print("Welcome to the Amazing Converter!\n")

def main():

    print("[1] Convert Temperature")
    print("[2] Convert Distance")
    print("[3] Convert Weight")

    again = True
    while True:
        try:
            choice = int(input("What would you like to convert? "))
        except ValueError:
            print("Invalid entry.")
        
        if choice == 1:
            print("[1] Convert from Celsius to Farenheit")
            print("[2] Convert from Farenheit to Celsius")
            temp_choice = int(input("Enter your choice: "))

            if temp_choice == 1:
                pass
            elif choice == 2:
                pass
                    
        elif choice == 2:
            print("[1] Convert from Miles to Kilometers")
            print("[2] Convert from Kilometers to Miles")
            dist_choice = int(input("Enter your choice: "))

            if dist_choice == 1:
                pass            
            elif dist_choice == 2:
                pass
            
        elif choice == 3:
            print("[1] Convert from Pounds to Kilos")
            print("[2] Convert from Kilos to Pounds")
            weight_choice = int(input("Enter your choice: "))

            if weight_choice == 1:
                pass
            elif weight_choice == 2:
                pass   

        again = input("Would you like to Convert another unit of measurement? ")
        if again == 1:
            True
        else:
            print("Have a good day!")
            break

if __name__ == "__main__":
    main()




#Convert Celsius to Farenheit
class Temperature:
    temp = 0
    def __init__(self, temp):
        self.temp = temp

    def cel_to_far(self):
        res = (self.temp * 9/5) + 32
        return res

celsius = float(input("Enter celsius value: "))  
far_temp = Temperature(celsius)
print(round(far_temp.cel_to_far()))



#Convert Farenheit to Celsius
class Temperature:
    temp = 0
    def __init__(self, temp):
        self.temp = temp

    def far_to_cel(self):
        res = (self.temp - 32) * 5/9
        return res

farenheit = float(input("Enter farenheit value: "))  
cel_temp = Temperature(farenheit)
print(round(cel_temp.far_to_cel()))


#Convert miles to kilometers
class Distance:
    dist = 0
    def __init__(self, dist):
        self.dist = dist

    def mil_to_kil(self):
        res = (self.dist * 1.609344)
        return res

miles = float(input("Enter mile value: "))
miles_dist = Distance(miles)
print(round(miles_dist.mil_to_kil()))



#Convert kilometers to miles
class Distance:
    dist = 0
    def __init__(self, dist):
        self.dist = dist

    def kil_to_mil(self):
        res = (self.dist * 0.62137)
        return res

kilometers = float(input("Enter kilometer value: "))
kilo_dist = Distance(kilometers)
print(round(kilo_dist.kil_to_mil()))


#Convert pounds to kilos
class Weight:
    def __init__(self, weight):
        self.weight = weight

    def pound_to_kilo(self):
        res = (self.weight * 0.45359237)
        return res

pounds = float(input("Enter pound value: "))
pound_weight = Weight(pounds)
print(round(pound_weight.pound_to_kilo()))


#Convert kilos to pounds
class Weight:
    def __init__(self, weight):
        self.weight = weight

    def kilo_to_pound(self):
        res = (self.weight / 0.45359237)
        return res

kilos = float(input("Enter kilo value: "))
kilo_weight = Weight(kilos)
print(round(kilo_weight.kilo_to_pound()))

Upvotes: 0

Views: 160

Answers (2)

user7362766
user7362766

Reputation:

Your created duplicated classes. so make them easier like

class Temperature:
    
    def cel_to_far(self, temp):
        res = (temp * 9/5) + 32
        return res

    def far_to_cel(self, temp):
        res = (temp - 32) * 5/9
        return res

and create object for that class, like this

def main():
    
    # creating object
    temperature = Temperature()

and calling that Temperature methods be like

        if choice == 1:
            print("[1] Convert from Celsius to Farenheit")
            print("[2] Convert from Farenheit to Celsius")
            temp_choice = int(input("Enter your choice: "))

            if temp_choice == 1:   
                celsius = float(input("Enter celsius value: "))  
                print(round(temperature.cel_to_far(celsius)))
            elif choice == 2:
                farenheit = float(input("Enter farenheit value: "))  
                print(round(temperature.far_to_cel(farenheit)))

Hoping, you got it.

Upvotes: 1

alani
alani

Reputation: 13079

You already have examples below each class of how to use that class. For example, below where your Temperature class is defined, you have:

celsius = float(input("Enter celsius value: "))  
far_temp = Temperature(celsius)
print(round(far_temp.cel_to_far()))

What you need to do is to move those to the relevant parts of main, where you want to use them. For example where you have:

            if temp_choice == 1:
                pass

you would put it (suitably indented) in place of the pass.

            if temp_choice == 1:
                celsius = float(input("Enter celsius value: "))  
                far_temp = Temperature(celsius)
                print(round(far_temp.cel_to_far()))

However, the other thing you need to do is to move the code which calls main, namely:

if __name__ == "__main__":
    main()

to the end of the module after the other classes have been defined.

If you try it as it is at the moment, you would get a NameError because the other classes have not yet been defined when main is called.

And in fact you don't really need the

if __name__ == "__main__":

unless you might also import your module into another one. If you know that you will only run it directly as a main program (python your_module.py) then it is sufficient just to put main() at the end.

Finally, it seems that your the classes for converting e.g. temperature in the two directions have the same name (both called Temperature). Whilst you could rename them to avoid a name conflict, they are in fact in a suitable form for merging into a single class that has both cel_to_far and far_to_cel methods, and similarly for the other classes.

Putting this all together (and removing the bit about repeating "would you like to convert another unit?" which is out of scope for this question), the code would look like this:

print("Welcome to the Amazing Converter!\n")

def main():

    print("[1] Convert Temperature")
    print("[2] Convert Distance")
    print("[3] Convert Weight")

    again = True
    while True:
        try:
            choice = int(input("What would you like to convert? "))
        except ValueError:
            print("Invalid entry.")
        
        if choice == 1:
            print("[1] Convert from Celsius to Farenheit")
            print("[2] Convert from Farenheit to Celsius")
            temp_choice = int(input("Enter your choice: "))

            if temp_choice == 1:
                celsius = float(input("Enter celsius value: "))  
                far_temp = Temperature(celsius)
                print(round(far_temp.cel_to_far()))
            elif temp_choice == 2:
                farenheit = float(input("Enter farenheit value: "))  
                cel_temp = Temperature(farenheit)
                print(round(cel_temp.far_to_cel()))
                    
        elif choice == 2:
            print("[1] Convert from Miles to Kilometers")
            print("[2] Convert from Kilometers to Miles")
            dist_choice = int(input("Enter your choice: "))

            if dist_choice == 1:
                miles = float(input("Enter mile value: "))
                miles_dist = Distance(miles)
                print(round(miles_dist.mil_to_kil()))

            elif dist_choice == 2:
                kilometers = float(input("Enter kilometer value: "))
                kilo_dist = Distance(kilometers)
                print(round(kilo_dist.kil_to_mil()))
            
        elif choice == 3:
            print("[1] Convert from Pounds to Kilos")
            print("[2] Convert from Kilos to Pounds")
            weight_choice = int(input("Enter your choice: "))

            if weight_choice == 1:
                pounds = float(input("Enter pound value: "))
                pound_weight = Weight(pounds)
                print(round(pound_weight.pound_to_kilo()))
            elif weight_choice == 2:
                kilos = float(input("Enter kilo value: "))
                kilo_weight = Weight(kilos)
                print(round(kilo_weight.kilo_to_pound()))


class Temperature:
    temp = 0
    def __init__(self, temp):
        self.temp = temp

    def cel_to_far(self):
        res = (self.temp * 9/5) + 32
        return res

    def far_to_cel(self):
        res = (self.temp - 32) * 5/9
        return res


class Distance:
    dist = 0
    def __init__(self, dist):
        self.dist = dist

    def mil_to_kil(self):
        res = (self.dist * 1.609344)
        return res

    def kil_to_mil(self):
        res = (self.dist * 0.62137)
        return res


class Weight:
    def __init__(self, weight):
        self.weight = weight

    def pound_to_kilo(self):
        res = (self.weight * 0.45359237)
        return res

    def kilo_to_pound(self):
        res = (self.weight / 0.45359237)
        return res


main()

Upvotes: 1

Related Questions