name 'Atno_to_Symbol' is not defined - python-3.x

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!

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.

Optionally passing parameters onto another function with jit

I am attempting to jit compile a python function, and use a optional argument to change the arguments of another function call.
I think where jit might be tripping up is that the default value of the optional argument is None, and jit doesn't know how to handle that, or at least doesn't know how to handle it when it changes to a numpy array. See below for a rough overview:
#jit(nopython=True)
def foo(otherFunc,arg1, optionalArg=None):
if optionalArg is not None:
out=otherFunc(arg1,optionalArg)
else:
out=otherFunc(arg1)
return out
Where optionalArg is either None, or a numpy array
One solution would be to turn this into three functions as shown below, but this feels kinda janky and I don't like it, especially because speed is very important for this task.
def foo(otherFunc,arg1,optionalArg=None):
if optionalArg is not None:
out=func1(otherFunc,arg1,optionalArg)
else:
out=func2(otherFunc,arg1)
return out
#jit(nopython=True)
def func1(otherFunc,arg1,optionalArg):
out=otherFunc(arg1,optionalArg)
return out
#jit(nopython=True)
def func2(otherFunc,arg1):
out=otherFunc(arg1)
return out
Note that other stuff is happening besides just calling otherFunc that makes using jit worth it, but I'm almost certain that is not where the problem is since this was working before without the optionalArg portion, so I have decided not to include it.
For those of you that are curious its runge-kutta order 4 implementation with optional extra parameters to pass to the differential equation. If you want to see the whole thing just ask.
The traceback is rather long but here is some of it:
inte.rk4(de2,y0,0.001,200,vals=np.ones(4))
Traceback (most recent call last):
File "<ipython-input-38-478197aa6a1a>", line 1, in <module>
inte.rk4(de2,y0,0.001,200,vals=np.ones(4))
File "C:\Users\Alex\Anaconda3\lib\site-packages\numba\dispatcher.py", line 350, in _compile_for_args
error_rewrite(e, 'typing')
File "C:\Users\Alex\Anaconda3\lib\site-packages\numba\dispatcher.py", line 317, in error_rewrite
reraise(type(e), e, None)
File "C:\Users\Alex\Anaconda3\lib\site-packages\numba\six.py", line 658, in reraise
raise value.with_traceback(tb)
TypingError: Internal error at <numba.typeinfer.CallConstraint object at 0x00000258E168C358>:
This continues...
inte.rk4 is the equiavlent of foo, de2 is otherFunc, y0, 0.001 and 200 are just values, that I swaped out for arg1 in my problem description above, and vals is optionalArg.
A similar thing happens when I try to run this with the vals parameter omitted:
ysExp=inte.rk4(deExp,y0,0.001,200)
Traceback (most recent call last):
File "<ipython-input-39-7dde4bcbdc2f>", line 1, in <module>
ysExp=inte.rk4(deExp,y0,0.001,200)
File "C:\Users\Alex\Anaconda3\lib\site-packages\numba\dispatcher.py", line 350, in _compile_for_args
error_rewrite(e, 'typing')
File "C:\Users\Alex\Anaconda3\lib\site-packages\numba\dispatcher.py", line 317, in error_rewrite
reraise(type(e), e, None)
File "C:\Users\Alex\Anaconda3\lib\site-packages\numba\six.py", line 658, in reraise
raise value.with_traceback(tb)
TypingError: Internal error at <numba.typeinfer.CallConstraint object at 0x00000258E048EA90>:
This continues...
If you see the documentation here, you can specify the optional type arguments explicitly in Numba. For example (this is the same example from documentation):
>>> #jit((optional(intp),))
... def f(x):
... return x is not None
...
>>> f(0)
True
>>> f(None)
False
Additionally, based on the conversation going on this Github issue you can use the following workaround to implement optional keyword. I have modified the code from the solution provided in the github issue to suit your example:
from numba import jitclass, int32, njit
from collections import OrderedDict
import numpy as np
np_arr = np.asarray([1,2])
spec = OrderedDict()
spec['x'] = int32
#jitclass(spec)
class Foo(object):
def __init__(self, x):
self.x = x
def otherFunc(self, optionalArg):
if optionalArg is None:
return self.x + 10
else:
return len(optionalArg)
#njit
def useOtherFunc(arg1, optArg):
foo = Foo(arg1)
print(foo.otherFunc(optArg))
arg1 = 5
useOtherFunc(arg1, np_arr) # Output: 2
useOtherFunc(arg1, None) # Output : 15
See this colab notebook for the example shown above.

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.

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