【发布时间】:2017-12-24 01:07:09
【问题描述】:
这里是 Python 新手。我正在编写一个具有计算两组坐标之间距离的方法的类。此方法需要 2 个参数:
- 房子的坐标对
- 地铁站坐标对
这是我的代码:
import pymysql.cursors
class Test(object):
def __init__(self):
self.create_connection()
def create_connection(self):
self.conn = pymysql.connect(host='localhost',
user='root',
password='',
db='testDB',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
self.cursor = self.conn.cursor()
def __del__(self):
self.c_coord()
self.q_coord()
self.calc_dist(cCoord, qCoord)
self.closeDB
def c_coord(self):
sql = "SELECT ID, coordinates from target where coordinates != 'NA'"
self.cursor.execute(sql)
# a dictionary cursor returns every row in the sql statement as a dictionary
cCoord = self.cursor.fetchall()
return cCoord
def q_coord(self):
sql = "SELECT station, coordinates from qSubway"
self.cursor.execute(sql)
qCoord = self.cursor.fetchall()
return qCoord
# return min subway and distance
def calc_dist(self, cCoord, qCoord):
print(cCoord)
print(qCoord)
def closeDB(self):
self.conn.close()
当我在 python 控制台中运行它时,这是我得到的:
slsu = 测试()
slsu.c_coord() [{'ID': 6221530552, '坐标': '40.745300,-73.861100'}, ...
slsu.q_coord() [{'station': '21st Street (IND Crosstown Line)', 'coordinates': '40.744591, -73.948674'}, ...
slsu.calc_dist(cCoord, qCoord) 回溯(最近一次通话最后): 文件“”,第 1 行,在 NameError: 名称 'cCoord' 未定义
我需要一些帮助来理解这个错误以及如何解决它?我想如果你将参数传递给函数,它应该会自动识别它吗?
【问题讨论】:
-
不,return 语句不会将
cCoord和qCoord的值保存到这些变量中,它只是返回它们。您需要将这些返回值分配给变量,然后将其传递给下一个函数
标签: python class methods arguments