Class Orientated Objects in Python error? - python-3.x

I've been having some issues with my code, you see I am a beginner at python programming and so I don't understand all the errors, So I would be quite happy for assistance down below is the code, which I have checked intensively just to find the error:
class Animal(object):
def __init__(self,legs,name):
def sleep(self,hours):
print("%s is sleeping for %d hours!" % (self.name,hours))
self.legs = legs
self.name = name
roscoe = Animal(4, "Canis Lupus Familiaris")
roscoe.name = ("Roscoe")
roscoe.sleep(4)
This is the Error:
Traceback (most recent call last):
File "class.py", line 9, in <module>
roscoe.sleep(4)
AttributeError: 'Animal' object has no attribute 'sleep'

You have a syntax error in the last line.
It should be:
roscoe.sleep(4)
instead of
roscue.sleep(4)
Giving more context since I see you're a begginner at Python. The traceback of Python interpreter (the "program" that runs Python code) tells you what happened. In this case, it says "name 'roscue' is not defined". This is usually a syntax error. Sometimes it can mean that you haven't defined that function. But in this case, it's the former.
Also, going a little bit further, you're probably going to get an error of indentation. In Python, you have to indent every block that you want to put together, either with tabs or with spaces.
Finally, think about your functions, you have to put them in order. Init is a function, and sleep is another function, so after each one you have a block. Different blocks should be indented separately. Here's how the code should look, but revise it instead of running it blindly.
class Animal(object):
def __init__(self,legs,name):
self.legs = legs
self.name = name
def sleep(self,hours):
print("%s is sleeping for %d hours!" % (self.name,hours))
roscoe = Animal(4, "Canis Lupus Familiaris")
roscoe.name = ("Roscoe")
roscoe.sleep(4)

Related

Why do the code shows tons of error whenever i type in alphabet input

I am new to python and I have an upcoming assignment that creates a menu that creates a function whenever the users enter the input. Here is the problem, whenever I enter a number the code shows a normal invalid option. For alphabetic input, however, it started to appear tons of errors. Does anyone know how to solve this issue
import turtle
wn = turtle.Screen()
poly = turtle.Turtle()
wn.setup(1000, 600)
poly.pensize(2)
poly.fillcolor('lightblue')
poly.penup()
poly.goto(-400, 15)
poly.pendown()
def menu():
print(' *********************************')
print('1. Draw polygons')
print('2. Draw a flower')
print('3. Exit')
task = int(input('Enter an option (1/2/3): '))
return task
def draw_shape(t, sides):
for i in range(0, sides):
t.forward(50)
t.stamp()
t.left(360 / sides)
t.forward(50)
def draw_flower(t, sides):
for i in range(0, sides):
t.left(90)
t.forward(100)
t.left(137.5)
t.forward(60)
t.left(80)
t.forward(70)
das = menu()
if das == 1:
for angle in [10, 9, 8, 7, 6, 5, 4, 3]:
poly.penup()
poly.forward(100)
poly.pendown()
poly.begin_fill()
draw_shape(poly, angle)
poly.end_fill()
elif das == 2:
poly.pencolor('cyan')
wn.bgcolor('light yellow')
poly.speed(4)
poly.penup()
poly.goto(0, 0)
poly.pendown()
draw_flower(poly, 52)
poly.forward(-100)
elif das == 3:
print('Program exists. Have a nice day')
exit()
else:
print('Invalid option')
. Draw polygons
2. Draw a flower
3. Exit
Enter an option (1/2/3): sa
Traceback (most recent call last):
File "C:/Users/jonny/PycharmProjects/untitled2/Polygon and flowers.py", line 40, in <module>
das = menu()
File "C:/Users/jonny/PycharmProjects/untitled2/Polygon and flowers.py", line 18, in menu
task = int(input('Enter an option (1/2/3): '))
ValueError: invalid literal for int() with base 10: 'sa'
Your Python interpreter is basically telling you that it cannot parse 'sa' into an int, which is to be expected right?
When prompted to enter an option, if you enter sa, input(...) returns exactly that: sa, as a string.
At that point in your script, task = int(input(...)) essentially becomes task = int('sa').
Exceptions
Now put yourself in the shoes of function int(): you receive a string, and you must return an integer.
What do you do when the input string, 'sa' for that matter, does not correctly represent an integer?
You cannot return an integer, because that would imply that you parsed the string successfully.
Returning something else than an integer would make no sense (and would be a pain to work with).
So you throw an exception: the execution flow is interrupted, and a specific kind of object, an exception, is thrown.
Exception handling
When a function throws an exception, it is interrupted: it does not finish running, it does not return anything, and the thrown exception is forwarded to the calling function. If that function decides to catch that exception (i.e. to handle it), then good, the normal execution flow can resume at that point.
If it decides not to handle the exception, then that function is interrupted too and the exception is forwarded yet again to the calling function. It continues in a similar fashion until the exception is caught, or until "no calling function is left", at which point the Python interpreter takes over, halts the execution of your script, and displays info about that exception (which is what happened in your case).
A first solution
If you're new to Python, maybe you shouldn't worry too much about handling exceptions right now. More generally, if you try to handle every possible case when it comes to user input, you're in for a wild ride.
For the sake of completeness though:
In order for your code to do what you expect, replace the das = menu() line with this:
try: # Enter a section of code where exceptions may be thrown
das = menu() # menu() may throw an exception because of the int(...) inside
except: # 'Catch' any exception that was thrown using an `except` block
das = -1 # Set a dummy, invalid value
With this code, if menu() throws an exception (when you enter sa for example), it will be caught: the try block will be interrupted, and the except block will be executed. das will receive value -1, which by the rest of your code is invalid, and thus Invalid option will be displayed. This is much better than having your whole script halted!
On the other hand, if no exception is thrown by menu(), the try block will reach its end normally, and the except block will not be executed.
A better solution
However, this is not ideal. The exception should not be handled around menu(), it should be handled around int(...) inside your menu function.
You could do this as an exercise: first handle the exception inside menu, and then try to loop over the int(input(...)) statement until a valid value is entered by the user.
There again, exception handling is not necessarily trivial and can be hard to get right, especially for beginners. So don't get frustrated if it seems like a not-so-useful overcomplication to you, there will come a point where you realize you can't go without them.
You can read more about exceptions here: https://www.w3schools.com/python/python_try_except.asp or here if you want a more comprehensive tutorial: https://docs.python.org/3/tutorial/errors.html
Hope this helps. :)

NameError: name 'XYZ' is not defined [ WARN:1] terminating async callback

I have a function 'draw_humans' in class 'TfPoseEstimator' in 'estimator.py' which is defined as:
def draw_humans:
global cocoDict
cocoDict = {}
cocoDict = dict(zip(a,zip(b,c)))
'''
'''
return (npimg, cocoDict, dist_dict)
I call this function in the main.py module and assign the returned values to variables like this:
image, cocoDict_clone, dist_dict_clone = TfPoseEstimator.draw_humans(image, humans, imgcopy=False)
But I get the error mentioned above.
Traceback (most recent call last):
File "run_webcam.py", line 306, in <module>
image, cocoDict_clone, dist_dict_clone = TfPoseEstimator.draw_humans(image, humans, imgcopy=False)
File "C:\Python\Python37\summer\PoseEstimation\tf_pose\estimator.py", line 772, in draw_humans
return (npimg, cocoDict, dist_dict)
NameError: name 'cocoDict' is not defined
[ WARN:1] terminating async callback
I have even tried to make it global but it did not work. Usually, it does work, can someone figure it out?
Actually, the problem was related to the scope of the variables (cocoDict in my case). This dictionary was initialized within the for loop but was being returned outside it. So, I declared it before the for loop and then after manipulating it within the for loop, returned it with no issues.
def draw_humans(npimg, humans, imgcopy=False):
global cocoDict
cocoDict = {}
for human in humans:
'''
'''
return (npimg, cocoDict, dist_dict)
I guess scope in Python is causing me a lot of efforts as I am from a C++ background.

Global variable values in PyCharm (Python 3.6) console

I'm new to both Python and PyCharm, so please forgive ignorance.
I was trying to tech myself about the execution of functions when initialising classes - specifically, I want to re-use a database connection object if passed into a new instance, but create one if not. I have a function get_cnx() that creates a connection. I discovered that, whether using a default argument in the __init__ statement to call get_cnx():
def __init__(self, db_cnx=get_cnx())
...or whether using a keyword argument:
self.db_cnx = kwargs.get('db_cnx', get_cnx())
...the function is always executed regardless of the presence (or content) of the connection argument that's passed in. Defeats the object of re-using a connection, so I reverted to an if condition. I believe there's a way of doing this with a decorator, but that felt like gilding the Lilly.
Anyway, this is the context for my actual question: to help me work out what was going on I created this simple test, as a module called "classes.py":
greeting = 'Good Day'
def my_func():
global greeting
greeting = 'Changed'
return 'Hello'
class Animal:
def __init__(self, greet):
if not greet:
self.greet = my_func()
else:
self.greet = greet
if __name__ == '__main__':
cat = Animal(None)
If I run this module (with "Run with Python console" checked in the configuration), I see the global variable greeting shown in blue as 'Changed', which is what I'd expect.
If I change the last bit to this:
if __name__ == '__main__':
cat = Animal('Wotcha')
I see the global variable shown in blue as 'Good Day', which is also what I'd expect.
However, when I then type this into the console:
dog = Animal(None)
...the global variable name turns red but still shows 'Good Day'.
Similarly, using the PyCharm console does the same thing:
>>> print(greeting)
Good Day
>>> dog = Animal(None)
>>> print(greeting)
Good Day
Now, I loaded the module into IDLE and hit F5 (run module), and in the console, did this:
>>> greeting
'Good Day'
>>> dog = Animal(None)
>>> greeting
'Changed'
This is what I would have expected to see in the PyCharm console.
Can someone explain what's going on? Could it be a bug, or is it my lack of understanding of the way PyCharm deals with scope? Or my lack of broader understanding of execution scope?
Thanks!!
JetBrains have opened a bug report for me - confirmed the behaviour isn't as expected.

Getting Python error, "TypeError: 'NoneType' object is not callable" SOMETIMES

Not very new to programming or to python but incredibly green to using pyunit. Need to use it for my new job and I keep getting this error but only sometimes when it is run. My code below.
import unittest
from nose_parameterized import parameterized
from CheckFromFile import listFileCheck, RepresentsFloat
testParams = listFileCheck()
class TestSequence(unittest.TestCase):
#parameterized.expand(testParams)
def test_sequence(self, name, a, b):
if RepresentsFloat(a):
self.assertAlmostEqual(a,b,2)
else:
self.assertEqual(a,b)
if __name__ == '__main__':
unittest.main()
What is happening here is that my test case is pulling a method listFileCheck from another class. What it does is it reads values from the serial port communicating with the control board and compares them with a calibration file. It puts the control board values in an MD array along with the calibration file values. These values can be either str, int, or float.
I used the test case to compare the values to one another however I keep getting this error but only sometimes. After every 3rd or so run it fails with this error.
Error
Traceback (most recent call last):
File "C:\Python34\lib\unittest\case.py", line 57, in testPartExecutor
yield
File "C:\Python34\lib\unittest\case.py", line 574, in run
testMethod()
TypeError: 'NoneType' object is not callable
Process finished with exit code 0
Anyone know why I might be getting this error on occasion?

AttributeError: tuple object has no attribute read_note()

OK So I have created 2 classes called Note and Notebook.
class Note:
""" A Note """
note_number = 1
def __init__(self, memo="", id=""):
""" initial attributes of the note"""
self.memo = memo
self.id = Note.note_number
Note.note_number += 1
def read_note(self):
print(self.memo)
class NoteBook:
"""The Notebook"""
def __init__(self):
self.note_book = []
def add_notes(self, *args):
for note in enumerate(args):
self.note_book.append(note)
def show_notes(self):
for note in self.note_book:
note.read_note()
n1 = Note("First note")
n2 = Note("Second note")
n3 = Note("Third note")
notebook1 = NoteBook()
notebook1.add_notes(n1, n2, n3)
notebook1.show_notes()
Traceback (most recent call last):
File "C:/Users/Alan/Python3/Random stuff/notebook revisions.py", line 47, in <module>
notebook1.show_notes()
File "C:/Users/Alan/Python3/Random stuff/notebook revisions.py", line 38, in show_notes
note.read_note()
AttributeError: 'tuple' object has no attribute 'read_note'
How come I get an attribute error? I want my show_notes() method to read all the notes in the notebook1 list.
Also if I print the following statement my result is the cryptic message:
print(notebook1.note_book[0])
(0, <__main__.Note object at 0x00863F30>)
How would I solve this problem to not produce the weird cryptic message and to print the strings "First note", "Second note" and "Third note".
Q1. Why the exception? As I suspected, the exception results from a bug in .add_notes. enumerate(args) turns notes into tuples containing a serial number and a note. This is wrong because notebooks should contain notes, not tuples, because notes already have a serial number, and because each call to add_note, and hence, enumerate, restarts at 0. Change add_note to
def add_notes(self, *args):
self.note_book.extend(args)
and notebook1.show_notes() produces what you seem to want.
First note
Second note
Third note
Q2. Better representation? For print(notebook1.note_book[0]) to print a tuple is wrong regardless of the content of the tuple. For testing, that line should have been part of the original script, just before the last line.
Printing a tuple prints the repr() of each element, so a custom __str__ will be ignored. With add_noted corrected, it now prints just the representation of the note.
<__main__.Note object at 0x00863F30>
To improve that, add back the __str__ method I asked you to delete, or a version thereof. I suggest you name it __repr__ instead, though.
def __repr__(self):
""" gives string of initial atrributes"""
return "Memo: {0}\nNote number: {1}\n ".format(self.memo, self.id)
# Note 1: First note
If you only define __str__, then __repr__ is still the mostly useless default (as above). If you define __repr__, then the custom function is used for both repr() and str(), the same as if you added the line __str__ = __repr__ after defining the latter.

Resources