0

来自包含在 for 循环中的另一个类的变量。调用它有问题

看我的例子

试图移动代码并制作全局变量,但没有奏效。

import requests

class Values:

    def get_crypto_data_dict(self):
        usd_url = "https://api.coingecko.com/api/v3/coins/markets?" \
                  "vs_currency=usd&order=market_cap_desc&per_page=250&page=1" \
                  "&sparkline=false&price_change_percentage=24h"
        gbp_url = "https://api.coingecko.com/api/v3/coins/markets?" \
                  "vs_currency=gbp&order=market_cap_desc&per_page=250&page=1" \
                  "&sparkline=false&price_change_percentage=24h"

        previous_request = None

        crypto_dict = None
        crypto_dict = dict()

        requests1 = requests.get(usd_url)
        results1 = requests1.json()

        requests2 = requests.get(gbp_url)
        results2 = requests2.json()

        for i in range(0, 250):
            crypto_dict[results1[i]['id']] = {
                'coin_name': results1[i]['name'],
                'changes': results1[i]['price_change_percentage_24h'],
                'usd': results1[i]['current_price'],
                'gbp': results2[i]['current_price']
            }


    # print(crypto_dict['bitcoin']['coin_name']) = will show coin name


class Portfolio(Values):

    def __init__(self, coin, holdings):
        self.coin = coin
        self.holdings = holdings

    def Get_User_Coins(self):
        continues = True
        coins_holdings = {}
        while (continues == False):
            coin = input("Enter the Coin Name i.e(Bitcoin(BTC) is bitcoin): ")
            holdings = input("Enter the  amount of holdings of the coin: ")
            print("\n")
            # Attatch to the current user


    def Pull_Coin_Dat(Values):
    # 'burst': {'coin_name': 'Burst', 'changes': 10.4028903177228, 'usd': 0.00425861382756581, 'gbp': 0.00329588603402332}}
    print()


    lol = Portfolio('xrp', 600)
    lol.Pull_Coin_Dat()

为了能够从 Pull_Coin_Dat 函数调用位于 Values 类中的 crypto_dict。

4

1 回答 1

0

您可以crypto_dict从以下位置返回字典get_crypto_data_dict()

return crypto_dict

然后调用里面的Pull_Coin_Dat(self)函数

called_crypto_dict = self.get_crypto_data_dict()

然后您可以从called_crypto_dict

为避免缩进错误,您需要将函数调用缩进为:

def Pull_Coin_Dat(Values):
    # 'burst': {'coin_name': 'Burst', 'changes': 10.4028903177228, 'usd': 0.00425861382756581, 'gbp': 0.00329588603402332}}
    called_crypto_dict = self.get_crypto_data_dict()
    print()
于 2019-02-19T04:25:18.700 回答