无法将类变量分配给给定值

时间:2017-09-09 21:37:04

标签: python oop

代码:

class YouTubeDownloader:
    ID=0
    Title =" "
    Description= " "
    PublishedAt =" "
    def IDFetch(self):
        IDRequest = "https://www.googleapis.com/youtube/v3/videos?id="+self+"&key="+APIKey+"&part=snippet"
        if len(list(self))==11:
            Data =requests.request(url=IDRequest,method="Get")
            Data = Data.json()
            ID= Data['items'][0]['id']
            self.ID = ID
        else:
            print("Wrong ID")

但是,我无法将self.ID分配给给定的值ID,它会产生以下问题:

Traceback (most recent call last):
  File "/home/x/x/red/simple.py", line 78, in <module>
    Data =YouTubeDownloader.IDFetch("jB8Vp1tgdbo")
  File "/home/x/x/red/simple.py", line 21, in IDFetch
    self.ID = ID
AttributeError: 'str' object has no attribute 'ID'

2 个答案:

答案 0 :(得分:1)

您正在调用IDFetch作为静态方法:

Data =YouTubeDownloader.IDFetch("jB8Vp1tgdbo")

相反,您必须在调用方法之前创建YouTubeDownloader的instanze:

class YouTubeDownloader:
    ID=0
    Title =" "
    Description= " "
    PublishedAt =" "
    def IDFetch(self, video_id):
        IDRequest = "https://www.googleapis.com/youtube/v3/videos?id="+video_id+"&key="+APIKey+"&part=snippet"
        if len(list(video_id))==11:
            Data =requests.request(url=IDRequest,method="Get")
            Data = Data.json()
            ID= Data['items'][0]['id']
            self.ID = ID
        else:
            print("Wrong ID")

downloader = YouTubeDownloader()
data = downloader.IDFetch("jB8Vp1tgdbo")

答案 1 :(得分:-2)

而不是:

self.ID = ID

地点:

YouTubeDownloader.ID = ID