简体   繁体   English

Python OOP:未定义变量。 范围问题是什么?

[英]Python OOP: Variable is not defined. What is the scope issue?

The error message is as follows: 错误消息如下:

Traceback (most recent call last):
  File "./bitcoin_price.py", line 57, in <module>
    Coindesk()
  File "./bitcoin_price.py", line 45, in Coindesk
    coindesk.pass_for_request()
  File "./bitcoin_price.py", line 39, in pass_for_request
    get_price = BtcAPI(url, api_id, json_tree)
NameError: name 'url' is not defined

What am I missing, here? 我在想什么? I'm guessing it is the coindesk.pass_for_request(), but I can't sort out exactly why the values don't get passed. 我猜是coindesk.pass_for_request(),但是我无法确切弄清为什么不传递值。 Also, what is a good way to debug something like this? 另外,调试这样的东西的好方法是什么? I'm having a rough time looking inside of the classes to see what is going on. 我在上课时花了很长时间,看看发生了什么。

class Price:


    def __init__(self, api_id, url, json_tree):

        self.api_id = api_id
        self.url = url
        self.json_tree = json_tree

    def pass_for_request(self):

        get_price = BtcAPI(url, api_id, json_tree)
        get_price.btc_api_call()


def Coindesk():

    coindesk = Price(api_id ="coindesk", url = "https://api.coindesk.com/v1/bpi/currentprice.json", json_tree = "['time']['updated']")
    coindesk.pass_for_request()

Try to replace 尝试更换

get_price = BtcAPI(url, api_id, json_tree)

with

get_price = BtcAPI(self.url, self.api_id, self.json_tree)

There is no url or api_id variable in the scope of pass_for_request . pass_for_request范围内没有urlapi_id变量。 You probably meant to access self.url and self.api_id , in python you have to use self. 您可能打算访问self.urlself.api_id ,在python中必须使用self. to access members unlike in other languages where using this. 访问成员不同于使用其他语言的成员this. is optional. 是可选的。

Also another thing I spotted is when you're trying to create a Price in Coindesk you are passing in api_id and the other arguments as if they are arguments with defaults, which they are not. 我发现的另一件事是,当您尝试在Coindesk创建Price ,您正在传递api_id和其他参数,就好像它们是具有默认值的参数一样,而并非默认值。 You'd need to call it as: Price("coindesk", "https://mylinktocoindesk", "['time']['updated']") 您需要将其称为: Price("coindesk", "https://mylinktocoindesk", "['time']['updated']")

Here's some reading on OOP in python that you might find helpful: https://docs.python.org/3/tutorial/classes.html https://www.tutorialspoint.com/python/python_classes_objects.htm 以下是一些有关python中的OOP的读物,您可能会发现有帮助: https : //docs.python.org/3/tutorial/classes.html https://www.tutorialspoint.com/python/python_classes_objects.htm

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

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