-2

我正在编写一个 python 程序,它应该从互联网上获取图像。因此我创建了一个主控制器和一个 APIService。因为我想让控制器更轻便,所以我在 APIServices 中添加了一些功能。

不幸的是,我无法调用 APIService 类中的其他函数,我总是收到错误消息:(“name 'fetch' is not defined”)。

有没有办法在类中调用方法,或者在 python 中不支持这种方法?

代码示例:

class APIService(object):
    def __init__(self, url):
         #init

    def fetch(url):
        #fetch Image 

    def fetchLogic(self, url):
          for i in url:
               fetch(i)    #here the error accures 



class Controller(object):        
      def __init__(self):
          #init

      def callAPI()
          api = APIService("url")
          api.fetchLogic([url1,url2])

if __name__ == "__main__":
    Controller()
4

3 回答 3

2

您必须调用self.fetch(i)而不是fetch(i),并接受以下self声明中的参数fetch

def fetch(self, url):
于 2020-07-26T18:04:17.570 回答
0

只需使用self.fetch(i)代替fetch(i)来访问类实例的方法。

于 2020-07-26T18:02:58.760 回答
0

问题就在那里

def fetch(url):
    # fetch image

fetch 函数不返回任何内容。

你必须编码fetch功能

def fetch(url):
    print('Supposed to fetch image, but return nothing now')

或者你可以做

from PIL import Image
import requests
from io import BytesIO


def fetch(url):
    response = requests.get(url)
    img = Image.open(BytesIO(response.content))
    return img

感谢@AndreasKuli的回答

于 2020-07-26T18:03:10.283 回答