python - 如何将类方法的输出打印到控制台?
问题描述
我有一个check_price
继承自约束的子类。我想查看清单unitPrices
。将列表打印unitPrices
到控制台以便我检查它的最简单方法是什么?
class check_price(Constraint):
def __init__(self, column):
self._column = column
def is_valid(self, table_data):
column_data = table_data[self._column_name]
group = table_data.groupby('StockCode')
unitPrices = group.apply(lambda x: x['UnitPrice'].unique())
print(unitPrices)
bulk = column_data >= 50
if bulk:
valid_price = column_data == min(unitPrices)
return bulk & valid_price
#test data
df = pd.DataFrame({
'Quantity': [100, 30, 40, 30,60],
'UnitPrice': [2.50, 5, 2, 3.99, 2.99],
'StockCode':['72083Z', '72083Z', '84006B', '22423S', '22423S']})
print(df)
解决方案
使用您发布的代码,您已经print(unitPrices)
在方法 is_valid 中进行了操作,该方法将在调用此方法时执行,因此假设您还想在任何其他时间打印此 unitPrices,那么您需要使用此类保存它的值,以便它随时可以访问,例如您可以这样做
class check_price(Constraint):
def __init__(self, column):
self._column = column
self.unitPrices = None #we initialize it to None because its value is calculate elsewhere
def is_valid(self, table_data):
column_data = table_data[self._column_name]
group = table_data.groupby('StockCode')
unitPrices = group.apply(lambda x: x['UnitPrice'].unique())
self.unitPrices = unitPrices # we save the calculate value
print(unitPrices)
bulk = column_data >= 50
if bulk:
valid_price = column_data == min(unitPrices)
return bulk & valid_price
并且可以这样使用
#do your stuff
my_check = check_price(some_data)
#do some other stuff
print(my_check.unitPrices)
像这样print(my_check.unitPrices)
将打印 None 如果is_valid
还没有被调用,但如果它是那么将打印它从最后一次is_valid
被调用的任何值
推荐阅读
- java - 如何从请求中的文件中获取 Rest-controller 中的 InputStream?
- laravel - 选择具有雄辩关系的列
- c++ - 浮点/整数类型转换的可靠溢出检测
- dji-sdk - 使用 DJI Onboard SDK 部署降落伞
- android - 初始化我的适配器时出现 ReResources$NotFoundException
- vue.js - 如何为 v-model 数据对象分配默认值
- ms-access - RmDir - 路径/文件访问错误 VBA
- node.js - 创建 HAPI 路由先决条件以从 REST API 中获取一些价值
- android - 应用程序在启动时意外崩溃
- java - 如何在不拆分字符串的情况下用其他字符串替换字符串