-3

How do I convert my fun.py into a module so that I can use it in 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())
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
曾建恩
  • 1
  • 1

1 Answers1

0

Few issues with your current code,

  1. In the methods of your class, you're just operating on the variables but not returning any data
  2. The import statement is wrong, there's nothing called a from where you're trying to import the file
  3. input() returns a string, you need to parse it into an integer if you want to do integer based operations on them.
# 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())
Shuvojit
  • 1,390
  • 8
  • 16
  • Oh! thanks your help,so if i'm defined the init, the def need having return some value? – 曾建恩 Apr 17 '19 at 08:46
  • Yes, the init is just a hook that's executed when an object of that class in initialised, nothing else. Your add/sub/mul/div functions has to return some value. – Shuvojit Apr 17 '19 at 09:46