Как сделать вызываемую функцию из моего класса python без необходимости запуска всего файла при вызове? - PullRequest
0 голосов
/ 12 марта 2020

Мне только что удалось создать coreCal c () Класс в Python. Все работает отлично. Теперь я хочу вызвать этот алгоритм из coreCal c () из другого файла python, без необходимости запускать весь исходный файл Class, я полагаю, потому что в настоящее время мой Class зависит от всего кода выше.

Может кто-нибудь подсказать, как решить этот вопрос?

**My code**:

   #references
   import gspread
   from oauth2client.service_account import ServiceAccountCredentials
   import pandas as pd
   import csv
   import time
   import requests

   #using creds to create a client to interact with the Google Drive API
    scope = ['https://spreadsheets.google.com/feeds',
             'https://www.googleapis.com/auth/drive']
    creds = ServiceAccountCredentials.from_json_keyfile_name('/Users/Miauw/Miauw/github/Miauw/Token/token.json', scope)
    client = gspread.authorize(creds)

    # Find a workbook by name and open the first sheet
    sheet = client.open("IFTTT_Webhooks_Events").sheet1

    #get data directly from google sheet.
    data = sheet.get_all_values()
    headers = data.pop(0)
    # capture data into dataframe
    df = pd.DataFrame(data, columns=headers)

    df_array = [ (df["Statement 3"].iloc[-1]),
        (df["Statement 2"].iloc[-1]),
        (df["Statement 3"].iloc[-1]),
        (df["Statement 3"].iloc[-1])
    ]

    #function for calculating user lonelienss based on UCLA Lonliness scoring (theory) 
    class coreCalc:
        def __init__(self):
        #assign loneliness-scores to the various user-responses
            for i in range(len(df_array)):
                if df_array[i] == 'Often':
                    df_array[i] = 3
                elif df_array[i] == 'Sometimes':
                    df_array[i] = 2
                elif df_array[i] == 'Rarely':
                    df_array[i] = 1
                elif df_array[i] == 'Never':
                    df_array[i] = 0
                #obtain sum of values for final scoring
            print(sum(map(int,df_array)))

    #coreCalc()

1 Ответ

0 голосов
/ 12 марта 2020

Единственный способ гарантировать, что этот код может быть вызван из другого модуля, - это импортировать модуль. К сожалению, у вас есть код инициализации в верхней части модуля. Я бы порекомендовал бросить все это внутри некоторого базового класса, а затем расширить его из coreCal c. Ниже я привел пример того, как это будет выглядеть.

#references
import csv
import time

import gspread
import requests
import pandas as pd
from oauth2client.service_account import ServiceAccountCredentials


class CalcBase:
    def __init__(self):
        #using creds to create a client to interact with the Google Drive API
        self.scope = ['https://spreadsheets.google.com/feeds',
                'https://www.googleapis.com/auth/drive']
        self.creds = ServiceAccountCredentials.from_json_keyfile_name('/Users/Miauw/Miauw/github/Miauw/Token/token.json', scope)
        self.client = gspread.authorize(creds)

        # Find a workbook by name and open the first sheet
        self.sheet = client.open("IFTTT_Webhooks_Events").sheet1

        #get data directly from google sheet.
        self.data = sheet.get_all_values()
        self.headers = data.pop(0)
        # capture data into dataframe
        self.df = pd.DataFrame(data, columns=headers)

        self.df_array = [ (df["Statement 3"].iloc[-1]),
            (df["Statement 2"].iloc[-1]),
            (df["Statement 3"].iloc[-1]),
            (df["Statement 3"].iloc[-1])
        ]

#function for calculating user lonelienss based on UCLA Lonliness scoring (theory) 
class coreCalc(CalcBase):
    def __init__(self):
        super().__init__(self)

    #assign loneliness-scores to the various user-responses
        for i in range(len(self.df_array)):
            if self.df_array[i] == 'Often':
                self.df_array[i] = 3
            elif self.df_array[i] == 'Sometimes':
                self.df_array[i] = 2
            elif self.df_array[i] == 'Rarely':
                self.df_array[i] = 1
            elif self.df_array[i] == 'Never':
                self.df_array[i] = 0
            #obtain sum of values for final scoring
        print(sum(map(int,self.df_array)))

#coreCalc()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...