Printing inside a method in python 3.x - python

I would like to print something inside the method. But the following code does not anything. But if I return the values I am able to print it outside the class. Why is it so? Any guidance would be great !
My code:
import pytest
class Test:
def __init__(self, val_1, val_2):
self.val_1 = val_1
self.val_2 = val_2
self.sum = 0
self.mul = 0
def sum_mul(self):
self.sum = self.val_1 + self.val_2
self.mul = self.val_1 * self.val_2
def ret_val(self):
return self.sum, self.mul
def test_exception(self,exception):
raise exception
return str(exception)
class Assert_Values:
def __init__(self, number, val_1, val_2, exception):
self.number = number
self.val_1 = val_1
self.val_2 = val_2
self.exception = exception
self.test_obj = Test(self.val_1, self.val_2)
def execute_test(self):
if self.number == 1:
self.test_obj.sum_mul()
self.val = self.test_obj.ret_val()
assert self.val == (self.val_1 + self.val_2, self.val_1 * self.val_2)
print (self.val)
elif self.number == 2:
with pytest.raises(self.exception):
self.exception_val = self.test_obj.test_exception(self.exception)
print (self.exception_val)
else:
print ("! Number not valid %d please enter another number" % (self.number))
assert_values = Assert_Values(2,4,5,ValueError)
assert_values.execute_test()

Pytest captures stdout; print() writes to stdout and you'll only see the output if there is a test failure.
Use the -s flag if you want to see stdout output instead:
py.test -s

Related

Parametrized RuleBasedStateMachine

After watching https://www.youtube.com/watch?v=zi0rHwfiX1Q I tried to port the example from C (implementation) and Erlang (testing) to Python and Hypothesis. Given this implementation (the rem function emulates %'s C behavior):
import math
def rem(x, y):
res = x % y
return int(math.copysign(res,x))
class Queue:
def __init__(self, capacity: int):
self.capacity = capacity + 1
self.data = [None] * self.capacity
self.inp = 0
self.outp = 0
def put(self, n: int):
self.data[self.inp] = n
self.inp = (self.inp + 1) % self.capacity
def get(self):
ans = self.data[self.outp]
self.outp = (self.outp + 1) % self.capacity
return ans
def size(self):
return rem((self.inp - self.outp), self.capacity)
and this test code
import unittest
from hypothesis.stateful import rule, precondition, RuleBasedStateMachine
from hypothesis.strategies import integers
from myqueue import Queue
class QueueMachine(RuleBasedStateMachine):
cap = 1
def __init__(self):
super().__init__()
self.queue = Queue(self.cap)
self.model = []
#rule(value=integers())
#precondition(lambda self: len(self.model) < self.cap)
def put(self, value):
self.queue.put(value)
self.model.append(value)
#rule()
def size(self):
expected = len(self.model)
actual = self.queue.size()
assert actual == expected
#rule()
#precondition(lambda self: self.model)
def get(self):
actual = self.queue.get()
expected = self.model[0]
self.model = self.model[1:]
assert actual == expected
TestQueue = QueueMachine.TestCase
if __name__ == "__main__":
unittest.main()
The actual question is how to use Hypothesis to also parametrize over QueueMachine.cap instead of setting it manually in the test class.
You can set self.queue in an initialize method rather than __init__, using a suitable integers strategy for the capacity.

how can i create a class inside a loop

Experiment
class calculator:
class add:
def __init__(self,*arg):
self.arg = arg
def display_new(self):
return sum(self.arg)
class multiply:
def __init__(self,*arg):
self.arg = arg
class multi_num:
def __init__(self,*arg):
self.arg = arg
def nature(self):
sum = 1
for x in arg:
sum=sum*x
return sum
class devide:
def __init__(self,x,y):
self.x = x
self.y = y
def display3(self):
try:
result = self.x/self.y
except ZeroDivisionError:
print("error: divided by zero")
else:
return (result)
calc = calculator()
multiply = calc.multiply(1,2,3,4,5)
multiply.display2()
its not displaying the result. how can I fix this and where am I making mistake ,add and divide is working properly but I don't know why this multiply is not working.
Change arg to self.arg:
def nature(self):
sum = 1
for x in self.arg:
sum=sum*x
return sum

python context protocol: why __enter__ and __exit__ method can't be defined in object? [duplicate]

Here is the code:
class Dummy(object):
def __init__(self, v):
self.ticker = v
def main():
def _assign_custom_str(x):
def _show_ticker(t):
return t.ticker
x.__str__ = _show_ticker
x.__repr__ = _show_ticker
return x
a = [Dummy(1), Dummy(2)]
a1 = [_assign_custom_str(t) for t in a]
print a1[1]
# print a1[1].__str__ # test to if orig __str__ is replaced
I was hoping to see the output like this
2
However, instead I see the standard representation:
<__main__.Dummy object at 0x01237730>
Why?
Magic methods are only guaranteed to work if they're defined on the type rather than on the object.
For example:
def _assign_custom_str(x):
def _show_ticker(self):
return self.ticker
x.__class__.__str__ = _show_ticker
x.__class__.__repr__ = _show_ticker
return x
But note that will affect all Dummy objects, not just the one you're using to access the class.
if you want to custmize __str__ for every instance, you can call another method _str in __str__, and custmize _str:
class Dummy(object):
def __init__(self, v):
self.ticker = v
def __str__(self):
return self._str()
def _str(self):
return super(Dummy, self).__str__()
def main():
a1 = Dummy(1)
a2 = Dummy(2)
a1._str = lambda self=a1:"a1: %d" % self.ticker
a2._str = lambda self=a2:"a2: %d" % self.ticker
print a1
print a2
a1.ticker = 100
print a1
main()
the output is :
a1: 1
a2: 2
a1: 100

How to replace an integer with a different class when it is assigned

I have a class called newInteger, and a variable called num, but I would like num to be a newInteger() instead of an int(). Code below.
class newInteger(int):
def __init__(self, value):
self.value = value
num = 10
I want the line num = 10 to act as if it is num = newInteger(10). Thanks to anyone who can help me with this.
You can run a small thread parallel to your main program that replaces all created integers to newInteger:
import threading
import time
class newInteger(int):
def __init__(self, value):
self.value = value
def __str__(self):
return "newInteger " + str(self.value)
def replace_int():
while True:
g = list(globals().items())
for n, v in g:
if type(v) == int:
globals()[n] = newInteger(v)
threading.Thread(target=replace_int, daemon=True).start()
num = 10
time.sleep(1)
print(num)
But this is unpythonic and will be realy hard to debug. You should just use a explicit conversion like #johnashu proposed
I am not sure if this is what you mean but if youassign the class to a variabl. then it will be an instance of that class..
example:
class newInteger(int):
def __init__(self, value):
self.value = value
num = 10
if num == 10:
num = newInteger(10)
prints:
hello

Undefined Function confusing

I have this bit of code here, and I was wondering why I was getting "total_with_tax is undefined"
This happens when I do:
c = Customer()
c.print_bill() --> this is where I get the error
Code:
class Customer:
def __init__(self):
self.total = 0
self.items_ordered = str("")
def add_to_order(self, NameOfItem, CostOfItem):
self.total += CostOfItem
self.items_ordered = self.items_ordered + (str(NameOfItem) + ", ")
def total_with_tax(self):
return ((self.total * 0.13) + self.total)
def print_bill(self):
print("----------------------------------------------")
print(self.items_ordered)
print("$%d" %(self.total))
print("$%d" %(total_with_tax()))
print("----------------------------------------------")
You need to prefix total_with_tax with self, like this:
print("$%d" % self.total_with_tax())

Categories