【问题标题】:Python: Trying to pass function arguments to another function within a class, get NameError: name ' ' is not definedPython:试图将函数参数传递给类中的另一个函数,得到 NameError: name ' ' is not defined
【发布时间】:2017-12-24 01:07:09
【问题描述】:

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

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 语句不会将 cCoordqCoord 的值保存到这些变量中,它只是返回它们。您需要将这些返回值分配给变量,然后将其传递给下一个函数

标签: python class methods arguments


【解决方案1】:

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

cCoord = c_Coord()
qCoord = q_Coord()

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

【讨论】:

  • 澄清一下,当使用'self'时,语法是:cCoord = self.c_Coord() qCoord = self.q_Coord()
猜你喜欢
  • 2023-01-27
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
  • 2023-03-11
  • 2022-12-02
  • 2019-02-18
  • 2012-05-22
相关资源
最近更新 更多