0

Total noob here. There are two python files in this example. The first is cloned from github, the second is my own. The first is called city_data.py. Mine is called analyze.py. Within the city_data.py code there is a class with a prompt with many defined functions within the class. In my analyze.py file I want to run a specific function within the class. I got the function to run (table output) but when I try to recall variables from the file it just says "NameError: name 'pop_dens' is not defined". Is there a way to recall the variable pop_dens from my file while running the function on the imported file?

city_data.py

class city_stats():
    prompt = '> '
        def table_output(self, arg):
            pop_dens = SingleTable(volume,'city')
            ...
            print(table)
            ...

analyze.py

from city_data import city_data

analyze = city_stats()

density_output = analyze.table_output("Chicago")
print(pop_dens)

run analyze.py

table outputs successfully
"NameError: name 'pop_dens' is not defined"
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
quada
  • 1

1 Answers1

0

When you want to access variable from another class use form class_name.class_variable. in your case

...
print(analyze.pop_dens)
...

Robot Mind
  • 321
  • 1
  • 6
  • This won't work unless `pop_dens` is an instance attribute. – cs95 Jun 24 '19 at 06:18
  • You are right. My bad :) – Robot Mind Jun 24 '19 at 06:26
  • this doesn't work. I get the error city_stats has no attribute pop_dens – quada Jun 24 '19 at 15:44
  • Sorry, I didn't cearfully read yours code. If you want this to work you need to modify class city_data. Add pop_dens = 0 or pop_dens =none in first line of class – Robot Mind Jun 24 '19 at 21:05
  • I was hoping to do this without modifying city_data.py since it will be frequently updated from github but when I add pop_dens = 0 in the first line of class it just returns 0 when I call it from analyze.py, even though the table output right above it displays pop_dens with the correct value. Any thoughts? – quada Jun 25 '19 at 03:30