![]() |
package addtion help - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: package addtion help (/thread-9233.html) |
package addtion help - PyMan - Mar-28-2018 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 ? RE: package addtion help - Gribouillis - Mar-29-2018 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 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 |