Python methods from csv

2024/10/5 14:49:57

I am working on an assignment where I create "instances" of cities using rows in a .csv, then use these instances in methods to calculate distance and population change. Creating the instances works fine (using steps 1-4 below), until I try to call printDistance:

##Step 1. Open and read CityPop.csv
with open('CityPop.csv', 'r', newline='') as f:
try:reader = csv.DictReader(f)##Step 2. Create "City" classclass City:##Step 3. Use _init method to assign attribute valuesdef __init__(self, row, header):self.__dict__ = dict(zip(header, row))##Step 4. Create "Cities" listdata = list(csv.reader(open('CityPop.csv')))instances = [City(i, data[0]) for i in data[1:]]##Step 5. Create printDistance method within "Cities" class  def printDistance(self, othercity, instances):dist=math.acos((math.sin(math.radians(self.lat)))*(math.sin(math.radians(othercity.lat)))+(math.cos(math.radians(self.lat)))*(math.cos(math.radians(othercity.lat)))*(math.cos(math.radians(self.lon-othercity.lon)))) * 6300 (self.lat, self.lon, othercity.lat, othercity.lon)

When I enter instances[0].printDistance(instances1) in the shell, I get the error:

 `NameError: name 'instances' is not defined`

Is this an indentation problem? Should I be calling the function from within the code, not the shell?

Example of how data is stored in csv

Answer

Nested functions must not contain self as parameter because they are not member functions. Class cannot pass instance variables to them. You are infact passing the same self from parent to child function.

Also you must not nest constructor, this is only for initiation purpose. Create a separate method indeed.

And try creating instance variable inside the constructor, and that is what init for !

self.instances = [self.getInstance(i, data[0]) for i in data[1:]]

Also create seperate function for instantiation

@classmethod
def getInstance(cls,d1,d2):return cls(d1,d2)
https://en.xdnf.cn/q/119059.html

Related Q&A

Convert string numpy.ndarray to float numpy.ndarray

I have one problem. How can I convert:import numpy as npa = np.array([[0.1 0.2 0.3], [0.3 0.4 0.5], [0.5 0.6 0.7]])To:b = np.array([[0.1,0.2,0.3], [0.3,0.4,0.5], [0.5,0.6,0.7]])

function at the end of code- why do i have to place it?

Im just starting my adventure with Python. Unfortunately, I cant figure out why, at the end of my code, I have to add myfunc(). Without it my code doesnt display. How is it if I use more than one def…

Would like to write code in idle that I have in Jupyter notebook. It is using Timeit

code big_array= np.random.rand(1000000) %timeit sum(big_array) this code above is done in jupyter notebook how do I use this code in idle

How to pass python variable to shell command [duplicate]

This question already has answers here:How to escape os.system() calls?(10 answers)Closed 2 years ago.Is their any way that i can pass variable value of python to my unix command Note : var is a pytho…

A function inside a function Python

This is a problem asked before but I cant really understand the other explain of this kind of problem so Im here to re-write it in more details. While studying I have encountered this kind of code tha…

Accessing a parameter passed to one function in another function

I have two functions:def f1(p1=raw_input("enter data")):...do somethingdef f2(p2=raw_input("enter data")):...do something elsep1 and p2 are the same data, so I want to avoid asking …

SOLVE: AttributeError: ImmutableDenseNDimArray object has no attribute as_independent

I am quite new to python and I have been trying to plot this in a few different ways. If I try using np.vectorize, it crashes. so i wrote this code, which is giving me the error in the title: import ma…

Python memory limit [duplicate]

This question already has answers here:In-memory size of a Python structure(7 answers)Closed 10 years ago.So clearly there cannot be unlimited memory in Python. I am writing a script that creates lists…

Automating Gmail login in Python

I am writing a Python program that can login Gmail.The purpose of this program is to check whether the username/password combination exists and is correct.Since this program is to test the the username…

Reversing order in incrementing digits

I have a list of numbers, and Im trying to do the following in a way as efficient as possible.For each consecutively incrementing chunk in the list I have to reverse its order.This is my attempt so far…