如何在Python的Sum类中实现add方法的链式调用以逐个处理列表元素
Solution for Chaining
add() Calls in the Sum Class Got it, let's break down how to modify your Sum class to match the Keras-style sequential add() pattern with chaining support. Here's a straightforward implementation:
Modified Sum Class Code
class Sum: def __init__(self): # Initialize our cumulative total to start at 0 self.total = 0 def add(self, num): # Add the single input number to our running total self.total += num # Return the instance itself to enable method chaining return self def get_total(self): # Helper method to safely retrieve the final sum return self.total
How to Use It
- Initialize the class:
sum_obj = Sum() - Chain multiple
add()calls (just like adding layers in Keras Sequential):sum_obj.add(5).add(8).add(2) - Get the final sum:
print(sum_obj.get_total()) # Output: 15
Key Details Explained
- Cumulative storage: We use
self.totalin the constructor to keep track of the running sum across alladd()calls. - Chaining magic: The
add()method returnsself(the current instance ofSum). This lets you call anotheradd()method immediately after the first, since you're operating on the same object every time. - Encapsulation: The
get_total()method is optional but recommended—instead of directly accessingsum_obj.total, using a method keeps your class's internal state encapsulated and makes future changes easier.
This setup mirrors the Keras Sequential workflow you referenced: you start with an empty instance, then build up your sum by adding elements one at a time, either via separate lines (sum_obj.add(5); sum_obj.add(8)) or chained calls.
内容的提问来源于stack exchange,提问作者Centy
相关产品推荐
相关产品推荐

