繁体   English   中英

类型错误:x 缺少 1 个必需的位置参数:y

[英]TypeError: x missing 1 required positional argument: y

我正在尝试将 function 从我的重构文件导入并调用到我的初始化文件中。 但是,当我尝试在其中一条路由中调用 function 时,我在终端中收到此错误,“ TypeError: show_state_locations() missing 1 required positional argument: 'test_code'

这是我的代码以及我如何导入所有内容:

重构

import requests
from privateinfo import key

def test_code(state, API_BASE_URL):
    url = f'https://covid-19-testing.github.io/locations/{state.lower()}/complete.json'
    res = requests.get(url)
    testing_data = res.json()
    latsLngs = {}
    for obj in testing_data:
          if obj["physical_address"]:

            for o in obj["physical_address"]:
                    addy = o["address_1"] 
                    city = o["city"]
                    phone = obj["phones"][0]["number"]

            location = f'{addy} {city}'
            res2 = requests.get(API_BASE_URL,
                                params={'key': key, 'location': location})

            location_coordinates = res2.json()
            lat = location_coordinates["results"][0]["locations"][0]["latLng"]["lat"]
            lng = location_coordinates["results"][0]["locations"][0]["latLng"]["lng"]
            latsLngs[location] = {'lat': lat, 'lng': lng, 'place': location, 'phone': phone}

在里面

from .refactor import test_code


@app.route('/location')
def show_state_locations(test_code):
    """Return selected state from drop down menu"""
    state = request.args.get('state')
    test_code(state, API_BASE_URL)

    return render_template('location.html', latsLngs=latsLngs)

您假设一个名称是从一个 function 调用到其外部 scope 的持久化:

def f():
    x = 1

f()
print(x)
NameError: name x is not defined

您需要在调用 scope 中返回值并将名称分配给x才能正常工作

def f():
    return 1

x = f()
x
1

请注意, return x也不起作用,因为它是返回的,而不是名称:

def f():
    x = 1
    return x

f()
x
# NameError!

x = f()
x
1

latLng也是如此:

def test_code():
    latLng = {}

test_code()
latLng = latLng
#NameError!

将其更改为

def test_code():
    latLng = {}
    ...
    return latLng

latLng = test_code()
latLng = latLng
# no error

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM