我需要通过python模块我的程序,我该怎么办

时间:2019-04-17 07:42:35

标签: python python-3.x

如何将我的fun.py转换为模块,以便可以在untitled.py中使用它?

fun.py

class test:      
    def __init__(self,num0,num1):
        self.num0 = num0
        self.num1 = num1

    def add(self):
        self.num0 + self.num1        

    def sub(self):
        self.num0 - self.num1

    def mul(self):
        self.num0 * self.num1

    def div(self):
        self.num0 / self.num1

untitled.py

  from a import fun
  a = eval(input('enter a:'))
  b = eval(input('enter b:'))
  test = fun.test(a,b)
  print(test.add())

1 个答案:

答案 0 :(得分:0)

您当前的代码很少出现问题,

  1. 在类的方法中,您只是对变量进行操作,而不返回任何数据
  2. import语句错误,您尝试从中导入文件的过程中没有任何东西称为
  3. input()返回一个字符串,如果要对其进行基于整数的操作,则需要将其解析为整数。
# fun.py
class test:      
    def __init__(self,num0,num1):
        self.num0 = num0
        self.num1 = num1

    '''
    You were just doing operations on variables, 
    you need to return the values as well
    '''
    def add(self):
        return self.num0 + self.num1        
    def sub(self):
        return self.num0 - self.num1
    def mul(self):
        return self.num0 * self.num1
    def div(self):
        return self.num0 / self.num1
# from {filename} import {class}
from fun import test

# You need to convert inputs into int() as input() returns string
a = int(input('enter a:'))
b = int(input('enter b:'))
test = test(a,b)
print(test.add())