Utilizing collections module in Python 3 - python-3.x

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.

Related

Class assignment: object not callable [duplicate]

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.

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)

Simple function won't run, beginner coder at work

I'm learning Python and it's early days for me. The following small bit of code won't run, the error message is
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'logdata' is not defined
The file is called "logdata.py". The faulty(?) code is;
def logthis(addme):
f=open("log.txt", "a+")
f.write(addme)
f.close()
logthis('teststring')
If there is a better place for a basic question like this please let me know, I'm sure i'll have plenty more to come as i learn Python, thanks!
I think, you have some extra lines of code in beginning of file which uses undefined identifier (variable, function etc.) with name logdata. Something like this.
>>> def f():
... print(logdata)
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
NameError: name 'logdata' is not defined
>>>
If so, just define/initialize that. Finally, your code will work fine then as I have already tested it as follows.
>>> def logthis(addme):
... f = open("log.txt", "a+")
... f.write(addme)
... f.close()
...
>>> logthis('teststring')
>>>
>>> # Read the newly created file content
...
>>> f = open("log.txt", "r")
>>> f.read()
'teststring'
>>>

name 'Atno_to_Symbol' is not defined

I am new to Python and have been studing -coding- every single exemple of the document many of you have probably gone through as well. In the class section I ran into an error I have not been able to get rid of. I appreciate your help, letting me know what does this (Atno_to_Symbol) do and how do I defined. I also would like to understand why that method retuns a 'C'. this is the code of the class:
class atom(object):
def __init__(self,atno,x,y,z):
self.atno=atno
self.position=(x,y,z)
def symbol(self): # a class method
return Atno_to_Symbol[atno]
def __repr__(self): # overloads printing
return '%d %10.4f %10.4f %10.4f' %(self.atno, self.position[0],self.position[1], self.position[2])
then this comes afterwards...
>>> at=atom(6,0.0,1.0,2.0)
>>> print(at)
6 0.0000 1.0000 2.0000
>>> at.symbol()
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
at.symbol()
File "<pyshell#56>", line 6, in symbol
return Atno_to_Symbol(atno)
****NameError: name 'Atno_to_Symbol' is not defined****
here I am supposed to get a 'C' instead fo that error
Thanks, fabianc!

python3 object has no attriubute

I have a file called entities.py, which contains the following code:
class EntityClass:
entities = {}
def __init__(self, parent=None):
.......
def show_all(self):
......
But then, when I run python 3 and type the command as follows:
>>> import entities
>>> ent = entities.EntityClass()
>>> ent.show_all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'EntityClass' object has no attribute 'show_all'
show_all should clearly be an attribute for EntityClass.
This of course worked perfectly in Python 2, and I'm assuming it's a Python 3 issue...
Is there a work around for this?
From the code posted, it looks like your indentation levels are wrong, you have declared the show_all() method on the module, not the class.
def_show_all(self): Should be indented to the same level as entities = {}
class EntityClass:
entities ={}
def __init__(self,parent=None):
.......
def show_all(self):
......

Resources