AttributeError: 'function' object has no attribute 'index' - python

I've made function which finds the list including specific word by input value.
I'd like to calling 'index' from 'search' function. But I've got Attribute error message like this ;
if distance.haversine([search.index]['geometry']['coordinates'][1],
[search.index]['geometry']['coordinates'][0],t_dicc['tuits']['coordinates']['latitud'],
t_dicc['tuits']['coordinates']['longitud']<=radius):
**AttributeError: 'function' object has no attribute 'index'**
I've tried to modify many times but it didn't work.
import os
import string
import json
from pprint import pprint
import distance
def main():
f = open('monumentos-reducido.json', 'r')
mo_dicc = json.load(f)
g = open('tuits.json', 'r')
t_dicc = json.load(g)
def search():
word = raw_input("monument name : ")
if(word in value for word in ('nombre')):
try:
StopIteration
if word > 1:
index = next(index for (index, d) in enumerate(mo_dicc['features']) if d["properties"]["nombre"] == word)
pprint(mo_dicc['features'][index])
except StopIteration:
exit()
search()
radius = input("radius(meters) : ")
def search2rad(search):
resultlst = []
if distance.haversine([search.index]['geometry']['coordinates'][1],[search.index]['geometry']['coordinates'][0], t_dicc['tuits']['coordinates']['latitud'], t_dicc['tuits']['coordinates']['longitud']<=radius):
index = next(index for (index, d) in enumerate(t_dicc['tuits']) if d['coordenadas'])
resultlst.append(t_dicc['tuits'][index])
print resultlst
search2rad(search)

You are making call to search2rad function as search2rad(search) where search is the function. Within search2rad(), you are doing:
if distance.haversine([search.index]['geometry']['coordinates'][1],[search.index]['geometry']['coordinates'][0], t_dicc['tuits']['coordinates']['latitud'], t_dicc['tuits']['coordinates']['longitud']<=radius):
Here you have mentioned search.index. It is raising error since it is function (with no attribute as index).
I think what you want to do is to pass the value returned by search() call to search2rad(). For that, you may do:
search2rad(search())
But the cleaner way will be to do it like:
index = search()
search2rad(index)

Related

Using a returned value from one class function to another [Python]

I was working on a project with Python NLTK and had some issues with the joiner() function being unable to retrieve a return value from another function within the same class, named open_file(). Was wondering how exactly the return function should work in this context and how I can fix this. Thanks everyone!
Code:
import nltk
nltk.download('wordnet')
from nltk.corpus import wordnet as wn
class Sentence:
def open_file(self):
file_vals = []
i = 0
with open("words.txt", "r") as my_file:
for line in my_file:
if i < 20:
stripped_line = line.strip()
file_vals.append(stripped_line)
i += 1
else:
print(file_vals)
return file_vals
def joiner(self, file_vals):
val_1 = wn.synsets(file_vals[0])[0].pos()
val_2 = wn.synsets(file_vals[1])[0].pos()
if val_1 == "n" and val_2 == "v":
print(val_1.capitalize() + " " + val_2 + ".")
my_obj = Sentence()
my_obj.open_file()
my_obj.joiner()
Just to note that you did not include the error message.
However, the apparent problem with your code is that methods defined in a class do not execute until the class is instantiated and the method called. This is why you cannot pass a value from one method to another inside an un-instantiated class. One way to achieve what I believe you want to do is:
This is assuming that all other parts of your code do not contain errors. Also, I did not try to run your code.
import nltk
nltk.download('wordnet')
from nltk.corpus import wordnet as wn
class Sentence:
def open_file(self):
file_vals = []
i = 0
with open("words.txt", "r") as my_file:
for line in my_file:
if i < 20:
stripped_line = line.strip()
file_vals.append(stripped_line)
i += 1
else:
print(file_vals)
return file_vals
def joiner(self, file_vals):
val_1 = wn.synsets(file_vals[0])[0].pos()
val_2 = wn.synsets(file_vals[1])[0].pos()
if val_1 == "n" and val_2 == "v":
print(val_1.capitalize() + " " + val_2 + ".")
my_obj = Sentence()
file_vals = my_obj.open_file()
my_obj.joiner(file_vals)
You have to first save the value returned by the 'open_file' method and then pass the returned value to 'joiner' as an argument.
The way you calling joiner() function is incorrect. Since the open_file() fucntion return variable file_vals and joiner() function as you defined is required file_vals as its argument, so you should pass the return result of open_file() function to joiner() function, for example:
my_obj = Sentence()
my_obj.joiner(my_obj.open_file())

Python function import

game_data = {}
def data_add(x):
game_data[x.__name__] = x
game_name = "notyet"
data_add(game_name)
print(game_data)
{ AttributeError: 'str' object has no attribute '__name__'
I want {'game_name'= 'notyet'}
You can get the behavior you want with a little added redundancy:
game_data = {}
def data_add(**params):
(key, value) = (list)(params.items())[0]
game_data[key] = value
game_name = "notyet"
data_add(game_name=game_name)
print(game_data)
Result:
{'game_name': 'notyet'}
The capability is the same. No abstraction is lost. If you can type the variable name once, you can type it twice.
There's likely a better way to do whatever you really want to accomplish with this pattern. Using the name of a variable like this is not a good practice. Variables hold data. Variables aren't themselves data.
Why not just do:
game_data = {}
def data_add(key, value):
game_data[key] = value
data_add("game_name", "notyet")
print(game_data)
Another option, which will give you the exact call to data_add that you want, is to associate the name with the value as a tuple that then can be passed in as a single positional parameter:
game_data = {}
def data_add(x):
game_data[x[0]] = x[1]
game_name = ("game_name", "notyet")
data_add(game_name)
print(game_data)

I am trying to import xml file with some empty attributes to table. getting this error AttributeError: 'NoneType' object has no attribute 'strip'

def XML_get_fields_and_types_and_data_levels_3(xml_file_name):
data_2d = []
for child in root:
grandchildren = child.findall(".//")
fields = []
types = []
data_1d = []
data_2d.append(data_1d)
for grandchild in grandchildren:
data_1d.append(convert_string_to_type(grandchild.text))
if grandchild.tag not in fields:
fields.append(grandchild.tag)
types.append(get_type_of_string(grandchild.text))
return (fields, types, data_2d)
def get_type_of_string(string):
clean_string = string.strip()
try:
if clean_string is not None:
clean_string = string.strip()
return string.strip()
if "." in clean_string:
clean_string = string.split()
if isinstance(clean_string, list):
point_or_segment = [float(i) for i in clean_string]
if len(point_or_segment) == 2:
return 'POINT'
else:
return 'LSEG'
else:
val = float(clean_string)
return 'REAL'
else:
val = int(clean_string)
return 'INTEGER'
except ValueError:
return 'TEXT'
the issue is the line-of-code (loc) after your method definition,
def get_type_of_string(string):
clean_string = string.strip()
there string might be None, so the exception is raised. Instead of re-writing the method for you, which would easy for me but not be very helpful for you, I suggest you to re-design this method. Here are my hints:
there is duplicated code
the split() method always returns a list, no matter if the separator is found, isn't, so there is no need for this line to exists if isinstance(clean_string, list)
then why is this conversion in place if then val is not used thereafter? the easiest way to evaluate a variable type is by using the isinstance() builtin method as you did it few lines above.
try to split this method, in simpler and smaller methods, or try to simplify its logic.
Hope this hints will help you through. Enjoy coding.

Tkinter: How to put user input into a list to access later?

When I try to access the list produced by the function stringToList, it always says TypeError: 'NoneType' object is not subscriptable.
class MyApp(Tk):
def __init__(self):
super().__init__()
# Many widgets defined and placed here
def my_fx(self):
def stringToList(input_str):
number_list = []
full_list = []
if list(input_str)[-1].isnumeric:
input_str += ","
for item in list(input_str):
if item.isnumeric():
number_list.append(item)
if not item.isnumeric():
num_str = ""
for item in number_list:
num_str += item
if int(num_str) not in full_list:
try:
full_list.append(int(num_str))
except ValueError:
pass
number_list = []
sorted_list = sorted(full_list).append(some_string)
return sorted_list
if True:
sorted_list = stringToList(some_entry_widget.get())
def do_stuff():
from my_other_file import my_other_fx
this_and_that = my_other_fx(sorted_list)
# More functions defined here
if __name__ == '__main__':
app = IntegratorApp()
app.mainloop()
This line in my_other_fx (which is properly named in my original code) is where I get the NoneType is not subscriptable error:
if sorted_list[-1] == some_value:
I've tried reworking stringToList so it uses IntVar and StringVar instead of regular int and str, but that didn't change anything. Why is it NoneType?
Also if anyone has other critique, it's more than welcome! I'm trying to learn!
EDIT: It seems to go "nope" and turn into NoneType when I try to append a string to the list. But why??
Try this:
full_list.append(some_string)
sorted_list = sorted(full_list)

Python function within function

I am reading LPTHW book and can't make this work
def raz(i):
word = i.split(' ')
return word
def prva(string):
word = raz(string) # should use raz function like in book example but it gives error instead
prva = word.pop(0)
return prva
I am trying to get first word with 'prva' function, to break my sentence I am trying to use 'raz' function... But it returns error:
"TypeError: 'list' object is not callable."
Probably doesn't matter but below I am using function like this:
file = 'test.txt'
normal = odpri(file)
prva = prva(normal)
print "%s" % prva
Cheers

Categories

Resources