-1

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()
Benipro98
  • 183
  • 2
  • 14

3 Answers3

2

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):
xzvf
  • 106
  • 5
0

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

fujiu
  • 501
  • 4
  • 9
  • 1
    there's also an issue with how `fetch` is defined. it's not a `@staticmethod`, so you also need to update the signature to `def fetch(self, url)` or add a `@staticmethod` decorator – anmaxvl Jul 26 '20 at 18:04
0

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

Ahmet
  • 7,527
  • 3
  • 23
  • 47