Home > database >  Cant access function in OOP python
Cant access function in OOP python

Time:09-11

For some reason, in my fruit scraper, i cannot access anything from listify function.
I'am getting an error, for exmaple: NameError: name 'family' is not defined.
And i cant figure out what is wrong with my code - is my function is bad, or i'am doing something wrong with class ?

import requests
import json
import random
import pickle

class FruitScraper():

    def __init__(self):
        self.name = []
        self.id = []
        self.family = []
        self.genus = []
        self.order = []
        self.carbohydrates = []
        self.protein = []
        self.fat = []
        self.calories = []
        self.sugar = []

    def scrape_all_fruits(self):
        data_list = []
        try:
            for ID in range(1, 10):
                url = f'https://www.fruityvice.com/api/fruit/{ID}'
                response = requests.get(url)
                data = response.json()
                data_list.append(data)
        except:
            pass
        return data_list


    def listify(self, stats):
        alist = json.dumps(self.scrape_all_fruits())
        jsonSTr = json.loads(alist)
        for i in jsonSTr:
            try:
                self.name.append(i['name'])
                self.id.append(i['id'])
                self.family.append(i['family'])
                self.genus.append(i['genus'])
                self.order.append(i['order'])
                self.carbohydrates.append(i['nutritions']['carbohydrates'])
                self.protein.append(i['nutritions']['protein'])
                self.fat.append(i['nutritions']['fat'])
                self.calories.append(i['nutritions']['calories'])
                self.sugar.append(i['nutritions']['sugar'])
            except:
                pass
        return stats

    def get_summary(self):
        for i in self.listify(zip(self.fat, self.protein, self.calories, self.sugar, self.carbohydrates, self.name)):
            nutr_stats = f'\nNutrients maximum statistics:\nFat: {max(self.fat)}\nProtein: {max(self.protein)}\nCarbohydrates: {max(self.carbohydrates)}\nCalories: {max(self.calories)}\nSugar: {max(self.sugar)}' \
                         f'\nNutrients minimum statistics:\nFat: {min(self.fat)}\nProtein: {min(self.protein)}\nCarbohydrates: {min(self.carbohydrates)}\nCalories: {min(self.calories)}\nSugar: {min(self.sugar)}' \
                         f'\nTotal fruits scraped: {len(self.name)}'
            return nutr_stats



Scraped_info = FruitScraper().scrape_all_fruits()

Listified_info = FruitScraper().listify(family)

Fruits_statistics = FruitScraper().get_summary()

It's my first time doing OOP.

CodePudding user response:

Please consider changing this

Scraped_info = FruitScraper().scrape_all_fruits()
Listified_info = FruitScraper().listify(family)
Fruits_statistics = FruitScraper().get_summary()

to

myScraper = FruitScraper()
Scraped_info = myScraper.scrape_all_fruits()
myScraper.listify()
Fruits_statistics  = myScraper.get_summary()

Otherwise you create three different objects of this class and discard them with all their attributes after running the individual method once.

This might also be critical to define family in this line of the code:

Listified_info = myScraper.listify(family)

But I can't see how you intended to use the parameter stats in your method listify(). It is just received and returned. I suggest that you change:

    def listify(self, stats):

to

    def listify(self):

and remove

        return stats

If you want to get those lists inside the object of this class returned by listify(), you may do the following (but this is not OOP way of doing things):

import requests
import json
import copy


class FruitScraper():
    def __init__(self):
        self.name = []
        self.id = []
        self.family = []
        self.genus = []
        self.order = []
        self.carbohydrates = []
        self.protein = []
        self.fat = []
        self.calories = []
        self.sugar = []


    def collect_all_lists(self):
        self.allLists = dict('name': self.name, 'id': self.id, 'family': self.family, 'genus': self.genus, 'order': self.order, 'carbohydrates': self.carbohydrates, 'protein': self.protein, 'fat': self.fat, 'calories': self.calories, 'sugar': self.sugar)


    def scrape_all_fruits(self):
        data_list = []
        try:
            for ID in range(1, 10):
                url = f'https://www.fruityvice.com/api/fruit/{ID}'
                response = requests.get(url)
                data = response.json()
                data_list.append(data)
        except:
            pass
        return data_list


    def listify(self):
        alist = json.dumps(self.scrape_all_fruits())
        jsonSTr = json.loads(alist)
        for i in jsonSTr:
            try:
                self.name.append(i['name'])
                self.id.append(i['id'])
                self.family.append(i['family'])
                self.genus.append(i['genus'])
                self.order.append(i['order'])
                self.carbohydrates.append(i['nutritions']['carbohydrates'])
                self.protein.append(i['nutritions']['protein'])
                self.fat.append(i['nutritions']['fat'])
                self.calories.append(i['nutritions']['calories'])
                self.sugar.append(i['nutritions']['sugar'])
            except:
                pass
        self.collect_all_lists()
        return copy.deepcopy(self.allLists)

    def get_summary(self):
        for i in self.listify(zip(self.fat, self.protein, self.calories, self.sugar, self.carbohydrates, self.name)):
            nutr_stats = f'\nNutrients maximum statistics:\nFat: {max(self.fat)}\nProtein: {max(self.protein)}\nCarbohydrates: {max(self.carbohydrates)}\nCalories: {max(self.calories)}\nSugar: {max(self.sugar)}' \
                         f'\nNutrients minimum statistics:\nFat: {min(self.fat)}\nProtein: {min(self.protein)}\nCarbohydrates: {min(self.carbohydrates)}\nCalories: {min(self.calories)}\nSugar: {min(self.sugar)}' \
                         f'\nTotal fruits scraped: {len(self.name)}'
            return nutr_stats


myScraper = FruitScraper()
Scraped_info = myScraper.scrape_all_fruits()
Listified_info = myScraper.listify()
Fruits_statistics = myScraper.get_summary()
  • Related