Issue with number of arguments in __init__() while using Inheritance - python-3.x

I am a beginner trying to perform inheritance using Python. So I decided to practice the example programs from the book "Data Structures and Algorithms in Python" by Michael T. Goodrich.
Here is the code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Progression:
def __init__(self,start=0):
self._current = start
def _advanced(self):
self._current += 1
def __next__(self):
if self._current is None:
raise StopIteration()
else:
answer = self._current
self._advanced()
return answer
def __iter__(self):
return self
def print_progression(self,n):
print(' '.join(str(next(self)) for j in range(n)))
class ArithmeticProgression:
def __init__(self,increment=1,start=0):
super().__init__(start)
self._increment = increment
def _advance(self):
self._current += self._increment
class GeometricProgression(Progression):
def __init__(self,base=2,start=1):
super().__init__(start)
self._base = base
def _advance(self):
self._current *= self._base
class FibonacciProgression(Progression):
def __init__(self,first=0,second=1):
super().__init__(first)
self._prev = second - first
def _advance(self):
self._prev, self._current = self._current,self._prev + self._current
if __name__ == '__main__':
print('Default Progression: ')
Progression().print_progression(10)
print('Arithmetic progression with increment 5 and start 2:')
ArithmeticProgression(5,2).print_progression(10)
print('Geometric progression with default base:')
GeometricProgression().print_progression(10)
print('Geometric progression with increasing it to the power of 2')
GeometricProgression(3).print_progression(10)
print('Fibonacci progression with default start progression')
FibonacciProgression().print_progression(10)
print('Fibonacci progression with default start progression')
FibonacciProgression(4,6).print_progression(10)
Here is the error:
Default Progression:
0 1 2 3 4 5 6 7 8 9
Arithmetic progression with increment 5 and start 2:
Traceback (most recent call last):
File "some location", line 61, in <module>
ArithmeticProgression(5,2).print_progression(10)
File "some location", line 33, in __init__
super().__init__(start)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
Any help will be appreciated. Here I am trying to check the super().init(start) of ArithmeticProgression but am getting very confused with the passing of elements in init() example. Any help will be appreciated. Also I am a beginner.

ArithmeticProgression does not inherit from Progression like GeometricProgression does. So there's no base class to call with super().
Replace
class ArithmeticProgression(Progression):
with
class ArithmeticProgression:
To make it short: you just forgot (Progression)

Related

Python Not printing expected output to screen from given thread

Could someone explain to me why my code doesn't print the expected output [Thread1 36] from the thread? I am currently using python3.7.0 on a mac OS Catalina 10.15.2
Here is my code:
import timeit, _thread
def expmod1(a, n, m):
return (a**n)%m
# avg_time is a higher order function
# argument is the different variations of the expmod(135, 202, 53) function
def avg_time(thread_name, expmod_function):
print("Start")
result = expmod_function(135, 202, 53)
print(thread_name + " " + str(result), flush=True)
return result
# analysis of all three functions based on average timecost using a constant function as defined by avg_time
def analysis1():
try:
_thread.start_new_thread(avg_time, ("Thread1", expmod1))
except:
print("Unable to start thread")
def main():
analysis1()
if __name__ == "__main__":
main()

Error when trying to communicate in Python

I want two scripts to communicate in python. I want them to know if the others have failed.
Doing what you see in the picture I have some questions. When I run rob2.py I automatically run rob1.py, why is this?
rob1.py
import simpy
import time
from rob2 import brok2
class Moving:
def __init__(self, env):
self.env = env
"""What does self.prov do?"""
self.prov = env.process(self.work())
self.broken = False
if self.broken == False:
global brok1
brok1 = 0
else:
brok1 = 0
#print(brok1)
def work(self):
while True:
yield env.timeout(20)
if brok2 == 1:
print("Robot 2 is not broken")
else:
print("Robot 2 is broken")
env= simpy.Environment()
moving = Moving(env)
env.run(until = 60)
rob2.py
import simpy
import time
from rob1 import brok1
class Placing:
def __init__(self, env):
self.env = env
"""What does self.prov do?"""
self.prov = env.process(self.work())
self.broken = False
if self.broken == False:
global brok2
brok2=1
else:
brok2 = 0
def work(self):
while True:
yield env.timeout(20)
time.sleep(5)
if brok1 == 1:
print("Robot 1 is not broken")
else:
print("Robot 1 is broken")
env= simpy.Environment()
placing = Placing(env)
env.run(until = 60)
And what have I done wrong when I get this message trying to run the scripts?
Traceback (most recent call last):
File "rob2.py", line 3, in <module>
from rob1 import brok1
File "/Users/erik/Python/python/rob1.py", line 3, in <module>
from rob2 import brok2
File "/Users/erik/Python/python/rob2.py", line 3, in <module>
from rob1 import brok1
ImportError: cannot import name 'brok1'
I came across some posts about zeroMQ, is that the way to go here?
The ImportError exception is thrown because Python detects a circular import loop: in one of your files you import the other one, which itself imports the first one, which import the second one and so on.
You will need to reorganize your code to avoid that.
Most (all?) programming languages will not like a circular import one way or another.

How can I catch an exception thrown in a function that I'm calling dynamically?

I got distracted and ended up writing a test framework in python. I'm struggling with a particular problem that this throws up.
During my assertion, I want to throw an exception as a way of bubbling a problem up to the run_test() method without requiring the user to have any knowledge of the framework. The problem is that when I do that, it seems that the try/catch block is not honoured.
Here is a cut down version of my fledgling framework:
# test_framework.py
import inspect
import module_containing_tests
class AssertionException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
def run_test(test_name, test_method):
try:
print(">", test_name)
test_method()
print("Passed")
except AssertionException as error:
print("Failed")
print(str(error))
def assert_true(conditional):
if not conditional:
raise AssertionException("Expected True. Was False")
def test(func):
func.is_test = True
return func
members = inspect.getmembers(module_containing_tests)
for member in members:
if "is_test" in dir(member[1]) and not member[0] == "module_containing_tests":
run_test(member[0], member[1])
The module containing the tests will look like this:
# module_containing_tests.py
from test_framework import *
#test
def passing_test():
assert_true(1 + 2 == 3)
#test
def failing_test():
assert_true(1 + 2 == 5)
The output has all the exception stack tracing in it and it also halts the execution
λ python test_framework.py
> failing_test
Traceback (most recent call last):
File "test_framework.py", line 29, in <module>
run_test(member[0], member[1])
File "test_framework.py", line 13, in run_test
test_method()
File "C:\Git\simpy-test\module_containing_tests.py", line 9, in failing_test
assert_true(1 + 2 == 5)
File "C:\Git\simpy-test\test_framework.py", line 20, in assert_true
raise AssertionException("Expected True. Was False")
test_framework.AssertionException: Expected True. Was False
What I want is something like this:
λ python test_framework.py
> failing_test
Expected True. Was False
Failed
> passing_test
Passed
I think the issue is partly in the circular reference between the two files that might mess up with the visibility of the methods (as somehow explained here) and partly, maybe, in the approach. If you think about how many other testing framework work, you often have 3 elements, the unit to test, the testing framework and a test runner.
So if we try to split everythig folllowing that logic you end up having:
test_framework.py
# test_framework.py
class AssertionException(Exception):
pass
def test(f):
f.is_test = True
return f
def assert_true(conditional):
if not conditional:
raise AssertionException("Expected True. Was False")
test_runner.py
# test_runner.py
import inspect
import unit_test
from test_framework import AssertionException
def run_test(test_name, test_method):
try:
print(">", test_name)
test_method()
print("Passed")
except AssertionException as error:
print("Failed with AssertionException: " + str(error))
except Exception as error:
print("Failed with Exception: " + str(error))
if __name__ == "__main__":
members = inspect.getmembers(unit_test)
for member in members:
if "is_test" in dir(member[1]):
run_test(member[0], member[1])
unit_test.py
# unit_test.py
from test_framework import *
#test
def a_passing_test():
assert_true(1 + 2 == 3)
#test
def z_failing_test():
assert_true(1 + 2 == 5)
With this setup the circular dependency is removed and all the visibility context are respected and the output/behaviour is the expected one.
I hope it helps.
Not sure this is what you want but this works.
Copied from here Hide traceback unless a debug flag is set
Output:
$ ./test_framework.py
> a_passing_test
Passed
> z_failing_test
test_framework.AssertionException: Expected True. Was False
First file:
#!/usr/bin/env python3
#test_framework.py
import inspect
import module_containing_tests
import sys
class AssertionException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
def run_test(test_name, test_method):
try:
print(">", test_name)
test_method()
print("Passed")
except AssertionException as error:
print("Failed")
print(str(error))
def assert_true(conditional):
if not conditional:
raise AssertionException("Expected True. Was False")
def test(func):
func.is_test = True
return func
sys.tracebacklimit=0
members = inspect.getmembers(module_containing_tests)
for member in members:
if "is_test" in dir(member[1]) and not member[0] == "module_containing_tests":
run_test(member[0], member[1])
second file:
#!/usr/bin/env python3
#module_containing_tests.py
from test_framework import *
#test
def a_passing_test():
assert_true(1 + 2 == 3)
#test
def z_failing_test():
assert_true(1 + 2 == 5)

Having trouble with Built-in Exception: ModuleNotFoundError

Having trouble with Built-in Exception: ModuleNotFoundError. I see nothing wrong with this solution, but am getting an Error. Checked out the docs but couldn't figure it out
folder structure
app
__init__.py
logic.py
test
__init__.py
test_logic.py
this error comes when i try to run the file from the command line directly --python test/test_logic.py
(tdd) D:\code\Outcome-15>coverage run test/test_logic.py
Traceback (most recent call last):
File "test/test_logic.py", line 3, in <module>
from app.logic import FizzBuzz
ModuleNotFoundError: No module named 'app'
logic.py
class FizzBuzz:
def fizz_buzz_service(self, num):
number_types = (int, float, complex)
if isinstance(num, number_types):
if num % 5 == 0 and num % 3 == 0:
return 'FizzBuzz'
elif num % 5 == 0:
return 'Buzz'
elif num % 3 == 0:
return 'Fizz'
else:
return num
else:
raise ValueError
test_logic.py
import unittest
from app.logic import FizzBuzz
class FizzBuzzServiceTestCases(unittest.TestCase):
"""
docstring for FizzBuzzServiceTestCases goes here!
"""
def setUp(self):
"""
Create an instance of fizz_buzz_service
"""
self.fizzbuzz = FizzBuzz()
def test_it_returns_a_number(self):
"""
Test for the default behavior of returning a number if not divisible by 3, 5 or both
"""
self.assertEqual(7, self.fizzbuzz.fizz_buzz_service(7))
def test_should_return_Fizz(self):
self.assertEqual("Fizz", self.fizzbuzz.fizz_buzz_service(3))
def test_should_return_Buzz(self):
self.assertEqual('Buzz', self.fizzbuzz.fizz_buzz_service(5))
def test_should_return_FizzBuzz(self):
self.assertEqual('FizzBuzz', self.fizzbuzz.fizz_buzz_service(15))
def test_should_return_error_message_if_arg_not_number(self):
with self.assertRaises(ValueError):
self.fizzbuzz.fizz_buzz_service('five')
if __name__ == '__main__':
unittest.main()

In Python 3, calling a Class function by name before init with inheritance

The goal:
B in inherits from A.
A and B have a factory method create, which harmonizes different input types before initializing the actual class.
create calls different create methods create_general_1, create_general_2, create_specific_b_1 via their name, supplied as a string.
This is my current approach:
import sys
class A:
def __init__(self, text):
self.text = text
print("I got initialized: {}".format(text))
def create(create_method_str):
# This is where it breaks:
create_method = getattr(sys.modules[__name__], create_method_str)
return create_method()
def create_general_style_3():
return A("a, #3")
class B(A):
def create_b_style_1():
return B("b, #1")
if __name__ == "__main__":
B.create("create_b_style_1")
It fails with the following error:
Traceback (most recent call last): File "test.py", line 22, in
B.create("create_b_style_1") File "test.py", line 10, in
create create_method = getattr(sys.modules[__name__],
create_method_str) AttributeError: 'module' object has no attribute
'create_b_style_1'
So in a way, I'm trying to combine three things: factory methods, inheritance, and function calling by name.
It would be great if someone had a smarter approach, or knew how to get this approach to work.
Thanks a great lot!
Thanks to Two-Bit Alchemist's comment, I've created this solution, which seems to work fine. Any improvements / other proposals are more than welcome :)
All is well explained here.
import sys
class A:
def __init__(self, text):
self.text = text
print("I got initialized: {}".format(text))
#classmethod
def create(cls, create_method_str):
create_method = getattr(cls, create_method_str)
return create_method()
#classmethod
def create_general_style_3(cls):
return cls("a, #3")
class B(A):
#classmethod
def create_b_style_1(cls):
return cls("b, #1")
if __name__ == "__main__":
B.create("create_b_style_1")

Resources