I have a simple function that works when I enter it in my Jython interpreter manually, but the call to len() fails when I try to run the code as a function.
def calculateChecksum(self, command):
sum = 0
for b in range(len(command)):
sum = sum + command[b-1]
mod = sum % 64
checkbyte = mod & (0xFF)
checksum = checkbyte | 0x80
where command is a jarray.array of bytes (Why am I not using the built-in array type? I ask you: Does it matter? jarray.array is working for everything else, and it clearly works on some occasions, see below)
>>> testarray
array([55, 57, 51], byte)
>>> len(testarray)
3
>>> stage.calculateChecksum(stage, testarray)
Traceback (innermost last):
File "<console>", line 1, in ?
File "....py", line 75, in calculateChecksum
AttributeError: __len__
So I think it's safe to say that this array implements len(), but I don't know why that doesn't always seem to be true. Any idea what's going on here?
Call the method like this:
stage.calculateChecksum(testarray)
Notice that you don't have to explicitly pass stage for the self parameter, that's passed implicitly when you invoke a method over an object (stage in this case.)
You defined def calculateChecksum(self, command): into a class, and when you call a class-method, you do not need to add the self variable. Python adds it for you.
Related
I got NameError for calling test_gobject, but the funny thing is I never called this function name. I called test_gobjectpy()
Can you explain it to me why Python decide to call the wrong function name (see error output)
Maybe it has some problems because I have a string with the same name as function?!
file name test_dyn_fun.py
second_path = ['test_gobject.py', 'st1.py', 'test_show_desktop.py', 'download_img.py', 'test_dump.py']
print("second_path", second_path)
print()
for i in second_path:
#func = create_dyn_func(i)
tmp = i.replace(".", "") #rm dot for function name
print("tmp =", tmp)
exec(f"def {tmp}(): print({i})")
print()
print(dir(test_gobjectpy))
print()
print(locals())
test_gobjectpy()
Error output:
Traceback (most recent call last):
File "/home/manta/Coding/test_dyn_fun.py", line 13, in <module>
test_gobjectpy()
File "<string>", line 1, in test_gobjectpy
NameError: name 'test_gobject' is not defined
In your loop you create functions, the first one created is effectively created like this:
i = 'test_gobject.py'
tmp = 'test_gobjectpy'
exec(f"def {tmp}(): print({i})")
So, it's as if you ran:
exec("def test_gobjectpy(): print(test_gobject.py)")
For Python to print test_gobject.py, it tries to access an object called test_gobject and its attribute .py.
That's what is causing the error. The fact that test_gobject.py looks like a filename to you doesn't matter, it's just names of variables to Python, the way you wrote it.
What would you expect to happen if you called this function?
def test_gobjectpy():
print(test_gobject.py)
More in general, as a beginning programmer, it's generally best to stay away from stuff like exec() and eval(). It's very common for new Python programmers to think they need this, or that it somehow solves a problem they have, but it's generally the worst solution to the problem and rarely actually a good solution at all. (not never, just rarely)
Given the following integers and calculation
from __future__ import division
a = 23
b = 45
c = 16
round((a/b)*0.9*c)
This results in:
TypeError: 'int' object is not callable.
How can I round the output to an integer?
Somewhere else in your code you have something that looks like this:
round = 42
Then when you write
round((a/b)*0.9*c)
that is interpreted as meaning a function call on the object bound to round, which is an int. And that fails.
The problem is whatever code binds an int to the name round. Find that and remove it.
I got the same error (TypeError: 'int' object is not callable)
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x(1-x))
return xl
... ... ... ...
>>> xlim(1,100,0,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in xlim
TypeError: 'int' object is not callable
after reading this post I realized that I forgot a multiplication sign * so
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x * (1-x))
return xl
xlim(1.0,100.0,0.0,0.0)
0.005
tanks
Stop stomping on round somewhere else by binding an int to it.
I was also facing this issue but in a little different scenario.
Scenario:
param = 1
def param():
.....
def func():
if param:
var = {passing a dict here}
param(var)
It looks simple and a stupid mistake here, but due to multiple lines of codes in the actual code, it took some time for me to figure out that the variable name I was using was same as my function name because of which I was getting this error.
Changed function name to something else and it worked.
So, basically, according to what I understood, this error means that you are trying to use an integer as a function or in more simple terms, the called function name is also used as an integer somewhere in the code.
So, just try to find out all occurrences of the called function name and look if that is being used as an integer somewhere.
I struggled to find this, so, sharing it here so that someone else may save their time, in case if they get into this issue.
In my case I changed:
return <variable>
with:
return str(<variable>)
try with the following and it must work:
str(round((a/b)*0.9*c))
Sometimes the problem would be forgetting an operator while calculation.
Example:
print(n-(-1+(math.sqrt(1-4(2*(-n))))/2)) rather
it has to be
print(n-(-1+(math.sqrt(1-4*(2*(-n))))/2))
HTH
There are two reasons for this error "TypeError: 'int' object is not callable"
Function Has an Integer Value
Consider
a = [5, 10, 15, 20]
max = 0
max = max(a)
print(max)
This will produce TypeError: 'int' object is not callable.
Just change the variable name "max" to var(say).
a = [5, 10, 15, 20]
var = 0
var = max(a)
print(var)
The above code will run perfectly without any error!!
Missing a Mathematical Operator
Consider
a = 5
b = a(a+1)
print(b)
This will also produce TypeError: 'int' object is not callable.
You might have forgotten to put the operator in between ( '*' in this case )
As mentioned you might have a variable named round (of type int) in your code and removing that should get rid of the error. For Jupyter notebooks however, simply clearing a cell or deleting it might not take the variable out of scope. In such a case, you can restart your notebook to start afresh after deleting the variable.
You can always use the below method to disambiguate the function.
__import__('__builtin__').round((a/b)*0.9*c)
__builtin__ is the module name for all the built in functions like round, min, max etc. Use the appropriate module name for functions from other modules.
I encountered this error because I was calling a function inside my model that used the #property decorator.
#property
def volume_range(self):
return self.max_oz - self.min_oz
When I tried to call this method in my serializer, I hit the error "TypeError: 'int' object is not callable".
def get_oz_range(self, obj):
return obj.volume_range()
In short, the issue was that the #property decorator turns a function into a getter. You can read more about property() in this SO response.
The solution for me was to access volume_range like a variable and not call it as a function:
def get_oz_range(self, obj):
return obj.volume_range # No more parenthesis
Given the following integers and calculation
from __future__ import division
a = 23
b = 45
c = 16
round((a/b)*0.9*c)
This results in:
TypeError: 'int' object is not callable.
How can I round the output to an integer?
Somewhere else in your code you have something that looks like this:
round = 42
Then when you write
round((a/b)*0.9*c)
that is interpreted as meaning a function call on the object bound to round, which is an int. And that fails.
The problem is whatever code binds an int to the name round. Find that and remove it.
I got the same error (TypeError: 'int' object is not callable)
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x(1-x))
return xl
... ... ... ...
>>> xlim(1,100,0,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in xlim
TypeError: 'int' object is not callable
after reading this post I realized that I forgot a multiplication sign * so
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x * (1-x))
return xl
xlim(1.0,100.0,0.0,0.0)
0.005
tanks
Stop stomping on round somewhere else by binding an int to it.
I was also facing this issue but in a little different scenario.
Scenario:
param = 1
def param():
.....
def func():
if param:
var = {passing a dict here}
param(var)
It looks simple and a stupid mistake here, but due to multiple lines of codes in the actual code, it took some time for me to figure out that the variable name I was using was same as my function name because of which I was getting this error.
Changed function name to something else and it worked.
So, basically, according to what I understood, this error means that you are trying to use an integer as a function or in more simple terms, the called function name is also used as an integer somewhere in the code.
So, just try to find out all occurrences of the called function name and look if that is being used as an integer somewhere.
I struggled to find this, so, sharing it here so that someone else may save their time, in case if they get into this issue.
In my case I changed:
return <variable>
with:
return str(<variable>)
try with the following and it must work:
str(round((a/b)*0.9*c))
Sometimes the problem would be forgetting an operator while calculation.
Example:
print(n-(-1+(math.sqrt(1-4(2*(-n))))/2)) rather
it has to be
print(n-(-1+(math.sqrt(1-4*(2*(-n))))/2))
HTH
There are two reasons for this error "TypeError: 'int' object is not callable"
Function Has an Integer Value
Consider
a = [5, 10, 15, 20]
max = 0
max = max(a)
print(max)
This will produce TypeError: 'int' object is not callable.
Just change the variable name "max" to var(say).
a = [5, 10, 15, 20]
var = 0
var = max(a)
print(var)
The above code will run perfectly without any error!!
Missing a Mathematical Operator
Consider
a = 5
b = a(a+1)
print(b)
This will also produce TypeError: 'int' object is not callable.
You might have forgotten to put the operator in between ( '*' in this case )
As mentioned you might have a variable named round (of type int) in your code and removing that should get rid of the error. For Jupyter notebooks however, simply clearing a cell or deleting it might not take the variable out of scope. In such a case, you can restart your notebook to start afresh after deleting the variable.
You can always use the below method to disambiguate the function.
__import__('__builtin__').round((a/b)*0.9*c)
__builtin__ is the module name for all the built in functions like round, min, max etc. Use the appropriate module name for functions from other modules.
I encountered this error because I was calling a function inside my model that used the #property decorator.
#property
def volume_range(self):
return self.max_oz - self.min_oz
When I tried to call this method in my serializer, I hit the error "TypeError: 'int' object is not callable".
def get_oz_range(self, obj):
return obj.volume_range()
In short, the issue was that the #property decorator turns a function into a getter. You can read more about property() in this SO response.
The solution for me was to access volume_range like a variable and not call it as a function:
def get_oz_range(self, obj):
return obj.volume_range # No more parenthesis
I'm new to Python, so please bear with me.
Why isn't Python throwing an error when it compiles the following code.
def b_search(left, right):
while left <= right:
mid = left + (right-left)//2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = whatever
else:
right = mid-1
return -1
Wondering how there's no error even though 'nums' isn't defined, and neither is 'whatever', nor 'target'.
Thanks!
Global variables are looked up at runtime, when the function tries to access their value, not when the function is defined. If there's still no nums variable when the function tries to actually use it, you'll get a NameError at that point, but not at function definition time.
The process here isn't "look up nums and compile bytecode using the information we found"; it's "compile bytecode that, if run, might look up nums then".
From the code you provided, looks like you're not running the function, therefore the code is not being executed and it doesn't use the non-existing variables.
Once you declared the function, if you try to call it, you'll find this errors:
>>> b_search(3,9)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in b_search
NameError: name 'nums' is not defined
i am trying to execute following code to understand Class data member in python, but it is throwing StopIteration error,
class PizzaShop():
pizza_stock = 10
def get_pizza(self):
while not PizzaShop.pizza_stock:
PizzaShop.pizza_stock -= 1
yield "take yours pizza order, total pizzas left {}".format(PizzaShop.pizza_stock)
mypizza_shop = PizzaShop()
pizza_order = mypizza_shop.get_pizza()
print "{}".format(repr(pizza_order.next()))
i am expecting that it should first print some message and then any exception
i am using python 2.7, ubuntu 32bits os
output:
Traceback (most recent call last):
File "/home/scott/pythonfiles/core_python/pizza.py", line 10, in <module>
print "{}".format(repr(pizza_order.next()))
StopIteration
The problem is this line
while not PizzaShop.pizza_stock:
This will stop immediately if pizza_stock is nonzero. Which it always is. You probably intended to write
while PizzaShop.pizza_stock:
Anyway, if you want to find the details on how values, classes, etc. behave in Python, you should check the docs. It's very different from Java.
P.S. The following is unnecessary as str.format has a shorthand for calling repr. Also, you shouldn't call magic methods like .next directly. Use the builtin next() instead.
print "{}".format(repr(pizza_order.next()))
Should be
print "{!r}".format(next(pizza_order))