Class assignment: object not callable [duplicate] - python-3.x

As a starting developer in Python I've seen this error message many times appearing in my console but I don't fully understand what does it means.
Could anyone tell me, in a general way, what kind of action produces this error?

That error occurs when you try to call, with (), an object that is not callable.
A callable object can be a function or a class (that implements __call__ method). According to Python Docs:
object.__call__(self[, args...]): Called when the instance is “called” as a function
For example:
x = 1
print x()
x is not a callable object, but you are trying to call it as if it were it. This example produces the error:
TypeError: 'int' object is not callable
For better understaing of what is a callable object read this answer in another SO post.

The other answers detail the reason for the error. A possible cause (to check) may be your class has a variable and method with the same name, which you then call. Python accesses the variable as a callable - with ().
e.g. Class A defines self.a and self.a():
>>> class A:
... def __init__(self, val):
... self.a = val
... def a(self):
... return self.a
...
>>> my_a = A(12)
>>> val = my_a.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>

The action occurs when you attempt to call an object which is not a function, as with (). For instance, this will produce the error:
>>> a = 5
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Class instances can also be called if they define a method __call__
One common mistake that causes this error is trying to look up a list or dictionary element, but using parentheses instead of square brackets, i.e. (0) instead of [0]

The exception is raised when you try to call not callable object. Callable objects are (functions, methods, objects with __call__)
>>> f = 1
>>> callable(f)
False
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

I came across this error message through a silly mistake. A classic example of Python giving you plenty of room to make a fool of yourself. Observe:
class DOH(object):
def __init__(self, property=None):
self.property=property
def property():
return property
x = DOH(1)
print(x.property())
Results
$ python3 t.py
Traceback (most recent call last):
File "t.py", line 9, in <module>
print(x.property())
TypeError: 'int' object is not callable
The problem here of course is that the function is overwritten with a property.

Related

Why can't iterable objects cant use the next() method directly?

Why can't iterable objects cant use the next() method directly?
I have tried the following code:
ite_obj = ["sudosuraz"]
#new_obj = iter(ite_obj)
while True:
try:
item = next(`ite_obj`)
print(item)
except StopIteration:
print("done!")
break
Output:
Traceback (most recent call last):
File "/home/suraz/python-learn/functions.py", line 5, in <module>
item = next(ite_obj)
TypeError: 'list' object is not an iterator

TypeError: 'tuple' object is not callable when converting a list to tuple as return value

I want to convert the final list as tuple. However i am receiving an error.How can i get rid of this?
li= [(19343160,),(39343169,)]
def render_list_sql(li):
l = []
for index, tuple in enumerate(li):
idd = str(tuple[0])
l.append(idd)
return tuple(l)
print(render_list_sql(li))
Expected value to be returned is:
(19343160,39343169)
Error
Traceback (most recent call last):
File "test.py", line 20, in <module>
print(render_list_sql(list))
File "test.py", line 14, in render_list_sql
return tuple(l)
TypeError: 'tuple' object is not callable
As commented, don't use names for variables that mean other things to Python. This is called "shadowing" and you lose the meaning of the original name.
Example:
>>> tuple # This is the class used to create tuples.
<class 'tuple'>
>>> for index,tuple in enumerate([1,2,3]): # This is similar to your code
... print(index,tuple)
...
0 1
1 2
2 3
>>> tuple # tuple is no longer a class, but an instance of an integer.
3
>>> tuple([1,2,3]) # so this fails
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not callable
>>> 3([1,2,3]) # You are basically doing this:
<interactive input>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not callable
So don't do that:
li = [(19343160,),(39343169,)] # don't reassign list
def render_list_sql(li):
l = []
for index, tup in enumerate(li): # don't reassign tuple
idd = str(tup[0])
l.append(idd)
return tuple(l) # now this will work
print(render_list_sql(li))
Output:
('19343160', '39343169')
FYI, a shorter version using a generator:
li = [(19343160,),(39343169,)]
tup = tuple(str(i[0]) for i in li)
print(tup)

What is the correct call for lists

Why is every time I set a variable as a list, it always comes back as TraceBack error when I try to append to the list:
>>> a = list
>>> a.append('item1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'append' requires a 'list' object but received a 'str'
>>> type(a)
<class 'type'>
list is not the attribute to define lists but it is a method to convert to lists. It is explained here.
What is the python attribute to define a variable as a list?
To initialize a var with a certain type, use () after the name of the class:
a = list()
You can also instatiate a list like this:
mylist = []

Utilizing collections module in Python 3

Relatively pointed question. Currently running Python 3.4.1 and am just working on an object-orientated exercise where I need to overwrite some functions from an inherited class.
Goal:
importing from builtin module collections and utilizing collections.UserList rewrite the append, extend so that it will not "add" any duplicates if detected. (this part accomplished)
Problem:
The main problem is that I still am learning object oriented programming and I want to build objects which can be easily typed in and returned so I am writing a str and repr for my class
Currently my class looks like the below: (omitted the "goal" stuff because it works)
import collections
class UList (collections.UserList):
def __init__(self, entry =[]):
self.entry = entry
def __str__ (self):
print (self.entry)
return
def __repr__(self):
return self.__str__()
Then I decide to run some sample code for good measure:
>>> x = UList ([4,5,6])
>>> x.entry
[4, 5, 6]
>>> x
[4, 5, 6]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x
TypeError: __repr__ returned non-string (type NoneType)
>>> print(x)
[4, 5, 6]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print(x)
TypeError: __str__ returned non-string (type NoneType)
usually I look straight to the objects and try to figure out what went wrong but I am a little confused as I am still new =(. Can someone help explain why it is returning a NoneType even after I have overwritten the init? (also, a possible solution on how I can rectify so no error would be extremely helpful)
Consider (note no explicit return at the end of __str__) :
>>> class Foo:
... def __str__(self):
... print('Foo!!')
...
>>> f=Foo()
>>> f
<__main__.Foo object at 0x10a655080>
>>> print(f)
Foo!!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __str__ returned non-string (type NoneType)
Vs:
>>> class Foo:
... def __str__(self):
... return 'Foo!!!'
...
>>> f=Foo()
>>> print(f)
Foo!!!
The issue is that __repr__ and __str__ need to return a return a string. The return from __repr__ should, if possible, be the 'official' string representation of the object for eval to recreate the object or some other <useful definition> according the the docs on __repr__
The docs on __str__ a more convenient or concise representation can be used' other than a Python expression.

TypeError: object.__new__() takes no parameters when using generators

I am a newbie in python.I need to print all the numbers from 1 to 100.When i run this code,i got this error
Traceback (most recent call last):
File "C:\Eclipse\workspace\firstpython\src\oopsegmant.py", line 14, in <module>
p = Prime(1)
TypeError: object.__new__() takes no parameters
The program is like this
class Prime():
def _init_(self,i):
self.i=i
def print_value(self):
while(True):
yield(self.i)
self.i+=self.i
p = Prime(1)
for numb in p.print_value():
if(numb>100):
break
print(numb)
_init_ should be spelled with double underscores, __init__.
All special methods names are enclosed in double underscores.
Also the print_value method should be indented under the class to be a part of it.

Resources