首页 > 解决方案 > 如何将类方法的输出打印到控制台?

问题描述

我有一个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)

标签: pythonpython-3.xdataframeclassoop

解决方案


使用您发布的代码,您已经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被调用的任何值


推荐阅读