Skip to main content
 首页 » 编程设计

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

2025年02月15日7dudu

这里是 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() 

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