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

时间:2018-02-04 06:12:57

标签: python oop

错误消息如下:

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

我想念的是什么?我猜它是coindesk.pass_for_request(),但我无法理清为什么值不会传递。另外,调试这样的东西的好方法是什么?我正在寻找课程内容,看看发生了什么。

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()

2 个答案:

答案 0 :(得分:1)

尝试替换

get_price = BtcAPI(url, api_id, json_tree)

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

答案 1 :(得分:1)

url范围内没有api_idpass_for_request变量。你可能想要访问self.urlself.api_id,在python中你必须使用self.来访问成员,这与使用this.是可选的其他语言不同。

我发现的另一件事是当你试图在Price Coindesk中创建api_id而你正在传递Price("coindesk", "https://mylinktocoindesk", "['time']['updated']")而其他参数就像是默认参数一样他们不是。您需要将其称为:- (IBAction)onBtnSaveAnim:(id)sender { //save animation for 3 seconds NSString *pathToMovie = [NSTemporaryDirectory() stringByAppendingPathComponent:ExportMovieFile]; unlink([pathToMovie UTF8String]); NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie]; GPUImageMovieWriter *movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(720, 1280)]; self.movieWriter = movieWriter; movieWriter.shouldPassthroughAudio = YES; [self.stillImageFilter addTarget:movieWriter]; self.stillImageSource.audioEncodingTarget = movieWriter; [movieWriter startRecording]; [GCDQueue executeInMainQueue:^{ [self.stillImageFilter removeTarget:movieWriter]; [movieWriter finishRecording]; [[KKAssetManager si] syncSaveVideoURL:[NSURL fileURLWithPath:pathToMovie]]; }afterDelaySecs:3];}

这里有一些关于python中OOP的阅读,你可能会觉得有用: https://docs.python.org/3/tutorial/classes.html https://www.tutorialspoint.com/python/python_classes_objects.htm