如何在Python类外部访问fix方法中更新后的test_date变量?
解决方法:获取fix方法中的test_date变量
你的问题核心是test_date是fix方法的局部变量,类外部无法直接访问,这里给你两种简单的解决方式:
方法1:让fix方法返回test_date
修改fix方法,在最后加上return语句,把处理后的test_date返回出去:
import pandas as pd class DayFix: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def fix(self): # 原有的日期修正逻辑 if self.month > 12: self.year += 1 self.month = 1 elif self.month == 2 and self.day > 29: self.month += 1 self.day = 1 elif self.month in [4,6,9,11]: if self.day > 30: self.month += 1 self.day = 1 elif self.month in [1,3,5,7,8,10]: if self.day > 31: self.month += 1 self.day = 1 elif self.month == 12 and self.day > 31: self.year += 1 self.month = 1 self.day = 1 # 用f-string简化日期拼接 test_date = f"{self.year}-{self.month}-{self.day}" tof = not pd.bdate_range(test_date, test_date).empty while not tof: self.day += 1 test_date = f"{self.year}-{self.month}-{self.day}" tof = not pd.bdate_range(test_date, test_date).empty # 返回处理后的日期 return test_date
调用时直接接收返回值:
d = DayFix(2020, 1, 10) result_date = d.fix() print(result_date) # 拿到处理后的日期字符串
方法2:将test_date设为实例属性
把test_date定义为self.test_date,类实例可以直接访问这个属性:
import pandas as pd class DayFix: def __init__(self, year, month, day): self.year = year self.month = month self.day = day self.test_date = "" # 初始化实例属性 def fix(self): # 原有的日期修正逻辑 if self.month > 12: self.year += 1 self.month = 1 elif self.month == 2 and self.day > 29: self.month += 1 self.day = 1 elif self.month in [4,6,9,11]: if self.day > 30: self.month += 1 self.day = 1 elif self.month in [1,3,5,7,8,10]: if self.day > 31: self.month += 1 self.day = 1 elif self.month == 12 and self.day > 31: self.year += 1 self.month = 1 self.day = 1 self.test_date = f"{self.year}-{self.month}-{self.day}" tof = not pd.bdate_range(self.test_date, self.test_date).empty while not tof: self.day += 1 self.test_date = f"{self.year}-{self.month}-{self.day}" tof = not pd.bdate_range(self.test_date, self.test_date).empty
调用后直接通过实例访问:
d = DayFix(2020, 1, 10) d.fix() print(d.test_date) # 获取处理后的日期
额外的新手优化建议
- 月份判断用
self.month in [4,6,9,11]替代多个or,代码更简洁易读 - 用f-string拼接日期比
str()+str()更高效,也更易维护 - 原代码2月的处理没考虑闰年,可借助
calendar.isleap(self.year)判断闰年,修正2月的最大天数 - 判断交易日的逻辑简化为
not pd.bdate_range(test_date, test_date).empty,比bool(len(...))更直观
内容的提问来源于stack exchange,提问作者Ryan Beckmann
相关产品推荐
相关产品推荐

