【问题标题】:How can I print output of a class method to console?如何将类方法的输出打印到控制台?
【发布时间】:2020-12-05 22:17:01
【问题描述】:

我有一个名为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)?你能澄清一下 1)你是如何运行程序的 2)是什么调用了打印(例如,你想要一个方法,你希望它在被调用时自动打印等)
  • 你叫打印就可以了?如果你的这个类没有以有用的方式打印,你定义一个__str__ 特殊方法
  • @anon01 1) 我调用其他一些类来加载数据 check_price 最后调用以检查数据 2) 我想我希望它被称为,我想看看@ 987654329@ 看起来像。使用函数我习惯于打印我需要执行此操作的对象。
  • 在这种情况下,您可以将打印件放在__init__
  • @Copperfield 据我了解,unitPrices 是在 is_valid 函数内初始化后生成的,因此在 init 中尝试打印 unitPrice 时出现错误。 __str__ 没有错误但也没有输出。你能建议任何其他检索列表unit prices的方法吗?

标签: python python-3.x dataframe class oop


【解决方案1】:

使用您发布的代码,您已经在方法 is_valid 中执行了print(unitPrices),该方法将在调用此方法时执行,因此假设您还想在任何其他时间打印此 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)

如果is_valid 还没有被调用,像这样的print(my_check.unitPrices) 将打印None,但如果它是那么将打印它自上次调用is_valid 以来的任何值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-05
    • 2012-06-01
    • 2021-12-13
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    相关资源
    最近更新 更多