繁体   English   中英

Python class(“名称'fetch'未定义”)

[英]Python class (“name 'fetch' is not defined”)

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

不幸的是,我无法在 APIService Class 中调用其他函数,我总是收到错误消息:(“未定义名称'fetch'”)。

有没有办法在 class 中调用方法,或者 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()

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

def fetch(self, url):

只需使用self.fetch(i)而不是fetch(i)来访问 class 实例的方法。

问题就在那里

def fetch(url):
    # fetch image

提取 function 不返回任何内容。

你必须代码fetch function

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的回答

暂无
暂无

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

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