I am having trouble understanding the following instructions in an exercise:
Create another class Location which has two properties called coordinate and name.
Each time an instance of Location is created, a class Coordinate should be created that gets passed in the coordinates that should be given as arguments when creating Location.
Further, you should create a return_location method that returns the name of the location.
An array locations which is a class variable of Location stores every Location that is created.
So far I have this:
class Coordinate:
def __init__(self,latitude,longitude):
self.latitude = latitude
self.longitude = longitude
def return_coord(self):
return self.latitude, self.longitude
class Location:
locations = [0]
def __init__(self,coordinate,name):
self.coordinate = coordinate
self.name = name
locations.append(self) #store every location created on the array locations
def return_location():
return self.name
But I am not sure if I am indeed doing the second step correctly
and when trying to do the 4th step it shows me the error: NameError: Name ´locations´ is not defined, did you mean Location?
CodePudding user response:
For the error you're receiving, you should be using Location.locations.append(self)
rather than locations.append(self)
CodePudding user response:
My understanding of step 2 is that Location.__init__()
should receive latitude
and longitude
as separate arguments, and you need to create a Location
instance from them.
There's no need to put 0
in the initial locations
list. It should start out empty, and you append to it when you create new Location
instances.
class Location:
locations = []
def __init__(self,lat, long,name):
self.coordinate = Coordinate(lat, long)
self.name = name
locations.append(self) #store every location created on the array locations
def return_location():
return self.name