Search code examples
pythonstringclassobjectgeolocation

how to create a string variable from multiple object attributes in python? how to calculate geographic distances?


I have created a class in python and it has multiple attributes. I want the object to create a new attribute based on those attributes. So, from street, city, state, and zip I want the object to create a string called address that can be used with geopy to find the distance between two of these objects. It says this below causes a conflict with float and string but I don't understand why this cannot be done.

Is there a way to calculate distance better than by doing this?

class warehouse:
def __init__(self, name, street, city, state, zip):
    self.name =name
    self.street = street
    self.city = city
    self.state = state
    self.zip = zip 

    self.address = self.street + ', ' + self.city + ', ' + self.state + ', ' + str(self.zip)

Solution

  • What you want to use here is str.format().

    For your use case, it'd be this:

    self.address = '{},{},{},{}'.format(self.street, self.city, self.state, self.zip)