Choosing default argument values in python? - python

This code keeps giving me the error:
TypeError: 'NoneType' object has no attribute 'getitem'
class d_exposure(object):
def __init__(self):
self.files = glob.glob('C:\files')
def exposure(self,level):
level = inspect.getargspec(d_exposure().exposure)[3][0]
print level
def main():
mp = d_exposure()
mp.exposure(level = 'MID')
It seems that the problem is that it wants a default value for level. However, the traceback shows it is getting a value.
Traceback (most recent call last):
File "C:\Users\Documents\my_scripts\exposure.py", line 58, in <module>
main()
File "C:\Users\Documents\my_scripts\exposure.py", line 54, in main
mp.exposure(level = 'MID')
File "C:\Users\Documents\my_scripts\exposure.py", line 17, in exposure
level = inspect.getargspec(d_exposure().exposure)[3][0]
When I try giving it a default value 'DIM', then the output has 'DIM', even though the call I made was mp.exposure(level = 'MID'). Can someone please help me figure out what I'm doing wrong?

inspect.getargspec(d_exposure().exposure)
This line gives you the following output:
ArgSpec(args=['self', 'level'], varargs=None, keywords=None, defaults=None)
The last entry in that is None, on which you are trying to call the getitem method by accessing the 0th element.
When you give default as 'DIM', the last value in the output of getargspec method is ['DIM'] and hence it gives you 'DIM' as the answer.
When you do this in the main method:
mp.exposure(level = 'MID')
you are giving MID as the parameter and not the default value. Default value can only be given during the function definition.
You haven't stated clearly what exactly you want to do instead, so I can't give you input on that.

Related

Python namedtuple: AttributeError: 'tuple' object has no attribute 'end_pos'

I have a class that starts as follows:
from collections import namedtuple
class Parser:
Rule = namedtuple('Rule', ['lhs', 'rhs', 'dot_pos', 'start_pos', 'end_pos'])
# __init__ ...
Since PyCharm detected all my tuple element namings correctly by giving me proper suggestions, I assumed I did it the right way so far, creating a little Rule class with the syntax shown above.
Now, I have a method within my Parser class that takes a Rule parameter:
def add(self, dot_rule: Rule):
print(dot_rule.end_pos)
# ...
Unfortunately, following error appears as soon as I try to call an element of dot_rule like end_pos:
AttributeError: 'tuple' object has no attribute 'end_pos'
What is it that I misunderstood when using namedtuple?
Edit: I call the method add the following way with lhs, rhs, and pos being some values calculated beforehand:
self.add((lhs, rhs, 0, pos, pos))
I thought since namedtuple is said to be backward-compatible with tuple this would be the correct syntax. Apparently, the parameter is now seen as a plain tuple instead of a Rule. What can I do differently here?
Edit 2: Traceback message:
Traceback (most recent call last):
File "...\earley.py", line 19, in <module>
main()
File "...\earley.py", line 14, in main
parser = Parser(grammar, lexicon, sentence)
File "...\parser.py", line 21, in __init__
self.parse(sentence)
File "...\parser.py", line 56, in parse
self.predict('S', i)
File "...\parser.py", line 41, in predict
self.add((lhs, rhs, 0, pos, pos)) # (X -> .α, i, i)
File "...\parser.py", line 24, in add
print(dot_rule.end_pos)
AttributeError: 'tuple' object has no attribute 'end_pos'
You can try this: essentially you were passing it a class tuple instead of the namedtuple called Rule. See:
Instead of self.add((lhs, rhs, 0, pos, pos))
Use self.add(Parser.Rule(lhs, rhs, 0, pos, pos))

how to use the variable which define before to set default value in python data class

I use decoration data class to initial variable but write the following code
class LRUCache(object):
capacity: int
map: dict = field(repr=False, default_factory=dict)
list: DoubleLinkedList = field(repr=False, default=DoubleLinkedList(capacity))
def print(self):
self.list.print()
and when I running this code I get a error
Traceback (most recent call last):
File "/Users/boker/code/PyhonCode/ComputerFoundation/computer_principle/cache/LRUCache.py", line 7, in <module>
class LRUCache(object):
File "/Users/boker/code/PyhonCode/ComputerFoundation/computer_principle/cache/LRUCache.py", line 10, in LRUCache
list: DoubleLinkedList = field(repr=False, default=DoubleLinkedList(capacity))
NameError: name 'capacity' is not defined
I have tried to find the solution in official document but I failed.How to settle this problem. I use python3.8.4.
As the error says (the value of) capacity isn't defined. If you want to set it to a default value just set it to whatever your default value is (e.g. capacity: int = 10)

Dont know how to solve error : AttributeError: 'str' object has no attribute 'set'

I am trying to fetch the result from the OptionMenu when it is clicked. However I keep getting the error.
>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\samue\AppData\Local\Programs\Thonny\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\samue\AppData\Local\Programs\Thonny\lib\tkinter\__init__.py", line 3440, in __call__
self.__var.set(self.__value)
AttributeError: 'str' object has no attribute 'set'
I don't know how to solve this as I want to be able to find the value that the user selects so I can use it within another function.
If it helps the words stored in the database are city names.
def destination_selected() :
selection = destination_choice.get()
print(selection)
def destination_dropdownbox_GUI():
destination = []
cursor.execute('SELECT DISTINCT Destination FROM FlightTable ')
row = str(cursor.fetchone())
x = 0
for x in row :
row = str(cursor.fetchone())
row = re.sub(r'\W+', '', row)
destination.append(row)
if row == 'None' :
break
destination.pop()
print(destination)
temp_dest = []
temp_dest = destination
print(temp_dest)
destination_dropdownbox = OptionMenu(window, *temp_dest,command = destination_selected).pack()
I expect an output of a city name. EG 'Oslo'
If you look at the documentation for the OptionMenu widget you'll see that after the master argument you must supply a variable. This parameter must be set to one of the special tkinter variables (StringVar, etc).
You aren't giving it a proper variable in this argument position, so tkinter is using the string you gave it as the variable. When you change the value, tkinter will call the set method. However, since you are passing a string rather than a variable, you get the error that str does not have a method named set.
The solution is to give the OptionMenu a variable. I'm guessing you've already defined this variable since your destination_selected method calls destination_choice.get().
Assuming that destination_choice is a special tkinter variable, you need to define your OptionMenu like this:
OptionMenu(window, destination_choice, *temp_dest,command = destination_selected).pack()

Gauss Elimination "Object has no attribute '__getitem__'"

Basically, I'm trying to code the Gauss Elimination(Foward) method, but, when executed, Python raises an exception saying: "Object has no attribute '__getitem__'" when the subtraction between 2 lists occurs.
The complete stacktrace is:
Traceback (most recent call last):
File line 35, in <module>
b=a.GaussForward()
File line 29, in GaussForward
self.a[index][w]=self.a[index][w]-aux[i][w]
TypeError: 'float' object has no attribute 'getitem'
I'll post the code below.
class TestGauss():
a=[]
def __init__(self,A):
self.a=A
def __getitem__(self,i):
return self.a[i]
def __setitem__(self,i,value):
self.a[i]=value
def GaussForward(self):
pivo=0.0
fact=0.0
aux=[]
for i in range(len(self.a)):
pivo=self.a[i][i]
for j in range(i+1,len(self.a[0])):
fact=self.a[j][i]/float(pivo)
print fact
for k in range(len(self.a[0])):
self.a[i][k]*=fact
for w in range(len(self.a[0])):
aux=self.a[i]
if i+1<len(self.a[0]):
index=i+1
self.a[index][w]=self.a[index][w]-aux[i][w]
print self.a
Your problem lies with aux[i][w]. Since you set aux=self.a[i], aux is a flat list (ie. not a list of lists) and thus when you try to access aux[i][w], you're trying to index self.a[i][i][w] which is not correct. I think you meant to do this:
self.a[index][w]=self.a[index][w]-aux[w]

'int' object has no attribute when calling recursive function in python

Not sure what is wrong with the Python code below. Will appreciate any help. I have looked into here and here, but could not solve my issue.
Code:
class myClass:
def factorial(n,self):
if n == 1:
return 1
else:
return n * self.factorial(n-1)
obj = myClass()
obj.factorial(3)
Error
Traceback (most recent call last):
File "a.py", line 9, in <module>
obj.factorial(3)
File "a.py", line 6, in factorial
return n * self.factorial(n-1)
AttributeError: 'int' object has no attribute 'factorial'
You transposed the parameter names for factorial. The one that refers to the object itself must come first. As it is, you're trying to access the factorial variable of the number that was passed in. Change your definition of factorial to this:
def factorial(self, n):
...
self needs to be the first argument to a class function. Change
def factorial(n,self)
to
def factorial(self, n)
change your method signature to
def factorial(self, n)
instead of
def factorial(n, self)
because when you call a class method via object. python expects reference to the class object as a first parameter. in your case it's 'int'. which is not reference to the class object.

Categories