简体   繁体   中英

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

I'm writing a python program, which should fetch images from the internet. Therefore I created a main controller and an APIService. Because I want to make the controller more light, I added some functionallity into the APIServices.

Unfortunally I cant call other functions within the APIService Class, I always get the error: ("name 'fetch' is not defined").

Is there a way to call methods inside a class or isnt this supported in 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 :

def fetch(self, url):

Simply use self.fetch(i) instead of fetch(i) to access the method of the class instance.

The problem is in there

def fetch(url):
    # fetch image

The fetch function does not return anything.

You have to code 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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