gpt4 book ai didi

Python:尝试将函数参数传递给类中的另一个函数,得到 NameError:未定义名称 ' '

转载 作者:太空宇宙 更新时间:2023-11-04 05:03:11 25 4
gpt4 key购买 nike

这里是 Python 新手。我正在编写一个类,该类具有计算两组坐标之间距离的方法。此方法采用 2 个参数:

  1. 一对房子的坐标
  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 = Test()

slsu.c_coord() [{'ID': 6221530552, 'coordinates': '40.745300,-73.861100'}, ...

slsu.q_coord() [{'station': '21st Street (IND Crosstown Line)', 'coordinates': '40.744591, -73.948674'}, ...

slsu.calc_dist(cCoord, qCoord) Traceback (most recent call last): File "", line 1, in NameError: name 'cCoord' is not defined

我需要一些帮助来理解这个错误以及如何修复它?我想如果你给函数传递一个参数,它应该会自动识别它?

最佳答案

您必须声明变量 cCoord 和 qCoord。函数不返回您可以使用的变量。将函数想象成一个黑盒子。它可以使用您给它的变量,但它所做的任何更改都不会影响该函数之外的任何内容。 return 命令只是意味着,如果您将变量设置为等于 c_Coord(),则该变量将具有函数返回的值。要解决此问题,请为您的两个 Coord 函数设置变量。

cCoord = c_Coord()
qCoord = q_Coord()

这两个函数都已运行,现在您可以在这些函数之外使用它们返回的内容。

关于Python:尝试将函数参数传递给类中的另一个函数,得到 NameError:未定义名称 ' ',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com