简体   繁体   English

为什么我的程序返回 NameError: name 'self' is not defined as the error

[英]Why is my program returning NameError: name 'self' is not defined as the error

I'm trying to get a program to tell me how many posts I've liked using the InstagramAPI module.我正在尝试获取一个程序来告诉我使用 InstagramAPI 模块我喜欢了多少帖子。 It's returning NameError: name 'self' is not defined and I'm not sure why.它返回NameError: name 'self' is not defined并且我不确定为什么。

This is my code:这是我的代码:

from InstagramAPI import InstagramAPI
import time, json, re
import json
import requests
import os
username = ''
password = ''

i = InstagramAPI(username, password)

i.login()

def getTotalLikedMedia(self, scan_rate=1):
        next_id = ''
        liked_items = []
        for x in range(0, scan_rate):
            temp = self.getLikedMedia(next_id)
            temp = self.LastJson
            try:
                next_id = temp["next_max_id"]
                for item in temp["items"]:
                    liked_items.append(item)
            except KeyError as e:
                break
        return liked_items

getTotalLikedMedia

self represents the instance of the class . self代表class的实例。 By using the argument bound to the name self we can access the attributes and methods of the class .通过使用绑定到名称self的参数,我们可以访问class的属性和方法。

You appear to be defining a method without the class it is supposed to be a method of.您似乎正在定义一种方法,而没有 class 它应该是一种方法。

class something:
   def __init__(self, something):
      self.something = something

ins = something()

Without posting entire traceback it is impossible to know what really happened.如果不发布整个追溯,就不可能知道到底发生了什么。 I guess that the code you posted is not how it really looks like on your computer.我猜你发布的代码并不是它在你的计算机上的真实样子。 It seems like a method definition but here it is just a plain function, where self is just an argument called... well, self.它看起来像是一个方法定义,但在这里它只是一个普通的 function,其中self只是一个名为……好吧,self 的参数。 Technically nothing is wrong with that, and calling that method would probably result in raising AttributeError , when the interpreter tries to execute line temp = self.getLikedMedia(next_id) , unless you passed as self some object that does have the method getLikedMedia() .从技术上讲,这没有任何问题,调用该方法可能会导致引发AttributeError ,当解释器尝试执行行temp = self.getLikedMedia(next_id)时,除非您作为self传递了一些 object 确实具有方法getLikedMedia()

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

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