【问题标题】:Need help calling a function from another class in python需要帮助从 python 中的另一个类调用函数
【发布时间】:2020-12-10 11:43:33
【问题描述】:

我写了一个简单的单位转换器程序。在 main() 类中,我有一个基本程序,要求用户选择要使用的转换器。然后我为每个转换器编写了一个特定的类。我想做的是将每个转换器方法导入 main.说实话,我不确定我是否需要 main()。无论如何,所有类都有效,我只是不知道如何将方法导入到它们适当的占位符中。我希望这是有道理的。

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()))

【问题讨论】:

    标签: python function class methods import


    【解决方案1】:

    您创建的重复类。所以让他们更容易像

    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
    

    并为该类创建对象,像这样

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

    并且调用温度方法就像

            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)))
    

    希望,你明白了。

    【讨论】:

    • 嘿 Arun_b,是的,我明白了!我为每个类都包含了这两种方法,而不是为每个方法创建不同的类。另外,我完全忘记在最后关闭 main() ,这就是它不起作用的原因。我赞成你的答案,但它没有显示,因为我的 15 声望点较少。
    • 没关系@RobinSage
    【解决方案2】:

    您已经在每个类下面提供了如何使用该类的示例。例如,在定义 Temperature 类的位置下方,您有:

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

    您需要做的是将这些移动到您想要使用它们的main 的相关部分。例如你有:

                if temp_choice == 1:
                    pass
    

    你可以用它(适当缩进)代替pass

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

    但是,你需要做的另一件事是移动调用main的代码,即:

    if __name__ == "__main__":
        main()
    

    在定义其他类之后到模块的末尾。

    如果你现在尝试它,你会得到一个NameError,因为在调用main 时还没有定义其他类。

    事实上你并不需要

    if __name__ == "__main__":
    

    除非您也可以将您的模块导入另一个模块。如果您知道您只会将其直接作为主程序运行 (python your_module.py),那么只需将 main() 放在末尾即可。

    最后,您的转换类似乎是两个方向的温度具有相同的名称(都称为Temperature)。虽然您可以重命名它们以避免名称冲突,但它们实际上是一种适合合并到具有 cel_to_farfar_to_cel 方法的单个类的形式,对于其他类也是如此。

    把所有这些放在一起(并删除关于重复“你想转换另一个单位吗?”这超出了这个问题的范围),代码看起来像这样:

    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()
    

    【讨论】:

    • 注意:刚刚看到有些类同名。即将处理这个...注意这个空间。
    • 阿拉尼维,非常感谢您的帮助!我已经用 main() 方法中的 PASS 替换了类中的代码。事实上,我已经完成了你建议的所有事情(除了对每个类使用两种方法而不是使用 2 个类(呃!)),但我忘了在最后关闭 main()。你提到不需要 if name == "main": 除非我要从另一个文件导入类。那会很好,这样我就可以只将 main() 保留在一个文件中,而将其他类保留在不同的文件中。如果你能告诉我怎么做,我将不胜感激。再次感谢您的帮助!
    • @RobinSage 你当然可以将类移动到另一个文件(比如myclasses.py),然后你所要做的就是from myclasses import Temperature, Distance, Weight。如果你这样做 - 使得这个模块只包含 main 函数,那么你想要将 this 模块导入另一个模块的可能性就更小了,所以更有理由不打扰一个if __name__ = '__main__': 测试,然后在底部调用main()
    • 好的!我会尝试让你知道。谢谢大家!
    猜你喜欢
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多