Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
package addtion help
#1
like this following example how can i do addition program.
class Mammals:
    def __init__(self):
        ''' Constructor for this class. '''
        # Create some member animals
        self.members = ['Tiger', 'Elephant', 'Wild Cat']
 
 
    def printMembers(self):
        print('Printing members of the Mammals class')
        for member in self.members:
            print('\t%s ' % member)
from Animals import Mammals
from Animals import Birds
 

myMammal = Mammals()
myMammal.printMembers()
like this i want to create addition,sub program where i type following program for addition but i want to put 2 addition numbers in test.py programs insted of taking 2 no's in shell.

class addition:
    def add():
        a=int(input("Enter the number : "))
        b=int(input("Enter the number two : "))
        c= a + b
        print(c)

obj = addition.add()
what i need to type in test file ?
Reply
#2
I wrote a way to do this by modifying the input() builtin function: suppose you have the module
# theaddition.py

class addition:
    def add():
        a=int(input("Enter the number : "))
        b=int(input("Enter the number two : "))
        c= a + b
        print(c)
Then you write the following test file
# testaddition.py

from fakeinput import fakeinput
from theaddition import addition

with fakeinput(['12', '19']):
    obj = addition.add()
Then you get the following output
Output:
λ python3 testaddition.py Enter the number : 12 Enter the number two : 19 31
To make this work, you need to save the following file
# fakeinput.py

import contextlib
import sys

@contextlib.contextmanager
def fakeinput(sequence):
    inp = MyInput(sequence)
    try:
        yield
    finally:
        inp.close()

class MyInput:
    def __init__(self, seq):
        self.seq = ('{}'.format(x) for x in seq)
        self.old = sys.modules['builtins'].input
        sys.modules['builtins'].input = self
        self.closed = False
    def __call__(self, s):
        try:
            v = next(self.seq)
        except StopIteration:
            self.close()
            return input(s)
        else:
            print(s, v, sep='')
            return v
    def close(self):
        if not self.closed:
            sys.modules['builtins'].input = self.old
            self.closed = True
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020