简体   繁体   English

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

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

I'm writing a python program, which should fetch images from the internet.我正在编写一个 python 程序,它应该从互联网上获取图像。 Therefore I created a main controller and an APIService.因此,我创建了一个主要的 controller 和一个 APIService。 Because I want to make the controller more light, I added some functionallity into the APIServices.因为我想让 controller 更轻,我在 APIServices 中添加了一些功能。

Unfortunally I cant call other functions within the APIService Class, I always get the error: ("name 'fetch' is not defined").不幸的是,我无法在 APIService Class 中调用其他函数,我总是收到错误消息:(“未定义名称'fetch'”)。

Is there a way to call methods inside a class or isnt this supported in python?有没有办法在 class 中调用方法,或者 python 不支持这种方法?

Code example:代码示例:

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

You must call self.fetch(i) instead of fetch(i) , aswell as accept the self argument in the decleration of fetch :您必须调用self.fetch(i)而不是fetch(i) ,并在fetch的声明中接受self参数:

def fetch(self, url):

Simply use self.fetch(i) instead of fetch(i) to access the method of the class instance.只需使用self.fetch(i)而不是fetch(i)来访问 class 实例的方法。

The problem is in there问题就在那里

def fetch(url):
    # fetch image

The fetch function does not return anything.提取 function 不返回任何内容。

You have to code fetch function你必须代码fetch function

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

or you could do或者你可以做

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

Thanks to @AndreasKuli for the answer感谢@AndreasKuli的回答

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

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