让全局变量变成局部变量

问题描述 投票:0回答:1

我正在创建一个程序,根据通话历史记录计算电信套餐的价格。这是主要功能。

from math import ceil

prev_date = None
expen_minutes_used = 0

def calculate_call_cost(row):
    
    global prev_date, cheap_minutes_used, expen_minutes_used 

    if prev_date is None or row['data of call'].date() != prev_date:
        prev_date = row['data of call'].date() 
        expen_minutes_used = 0

    expen_minutes = 0
    if expen_minutes_used < 5:
        expen_minutes = min(5 - expen_minutes_used, ceil(row['Duration in second'] / 60))
                        
        expen_minutes_used += expen_minutes 

    cheap_minutes = ceil(row['Duration in second'] / 60) - expen_minutes
                    
    
    cost = cheap_minutes * 0.40 + expen_minutes * 3.95
    return cost

# calls_data_sorted['Cost of tariff'] = calls_data_sorted.apply(calculate_call_cost, axis = 1) 
total_cost2 = calls_data_sorted['Cost of tariff'].sum()
calls_data_sorted

请告诉我有什么方法可以将这些全局变量更改为局部变量。

python pandas dataframe global-variables local-variables
1个回答
0
投票

将调用之间需要保持的状态放入字典中。将其作为参数传递给

calculate_call_cost()
,该函数可以更新字典。

from math import ceil

state_dict = {'prev_date': None, 'expen_minutes_used': 0}

def calculate_call_cost(row, state: dict):
    if state['prev_date'] is None or row['data of call'].date() != state['prev_date']:
        state['prev_date'] = row['data of call'].date() 
        state['expen_minutes_used'] = 0

    expen_minutes = 0
    if state['expen_minutes_used'] < 5:
        expen_minutes = min(5 - state['expen_minutes_used'], ceil(row['Duration in second'] / 60))
                        
        state['expen_minutes_used'] += expen_minutes 

    cheap_minutes = ceil(row['Duration in second'] / 60) - expen_minutes
                    
    
    cost = cheap_minutes * 0.40 + expen_minutes * 3.95
    return cost

calls_data_sorted['Cost of tariff'] = calls_data_sorted.apply(lambda row: calculate_call_cost(row, state_dict), axis = 1) 
total_cost2 = calls_data_sorted['Cost of tariff'].sum()

您还可以使用

calculate_call_cost()
作为方法来创建一个类。需要持久化的变量可以是类的属性。

© www.soinside.com 2019 - 2024. All rights reserved.