Home > database >  Call a method n times by appending it to itself in a python object
Call a method n times by appending it to itself in a python object

Time:04-19

Say i have a python class Sum() with a method add() that can take a list of numbers for manipulation, say

sum = Sum()
sum.add([5, 8, 2])

I want to instead call the .add method on each list item by 'appending' to itself. How can i achieve this?

sum.add(5).add(8).add(2)

For clarity, i have seen the two implementations in keras

model = tf.keras.Sequential([
   hub_layer,
   tf.keras.layers.Dense(16, activation='relu'),
   tf.keras.layers.Dense(1)
])

Which can also be represented as

model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))

I want to achieve the second for the above scenarios, whereby I call the .add method n times for each item I have in a list

CodePudding user response:

You can call the method add on Sum objects. Let's decompose the line

sum.add(5).add(8)

add(5) is applied to the Sum object sum.

add(8) must be applied to a Sum object as well, so sum.add(5) must return a Sum object as well.

In general the add method must return a Sum object

CodePudding user response:

in your add function, simply return object itself

def add(self, number: int):
    # do your stuff
    return self

this works because the next .add is going to be executed on the returned element of the previous .add (aka the object itself)

hope it helps :)

CodePudding user response:

For being able to chain methods, you need the method to return the instance of the object (aka self). You can find some additional information here.

If you object sum has a method add, then you can write sum.add(x). However, you can't call add on anything, you can only call it on instances of this class Sum. So if you want to do sum.add(x).add(y), you need that sum.add(x) is an instance of Sum, so the add method should return a Sum instance. If you want the object itself to be modified (and not create another one), you need add to return self.

CodePudding user response:

Just return self in your add method:

class Sum:
  def __init__(self, l = []):
    self.l = l
  def add(self, el):
    self.l.append(el)
    return self
  def get(self):
    return self.l

sum = Sum()
sum.add([5, 8, 2]).add([5, 2])
sum.add([33, 2])
print(sum.get())
[[5, 8, 2], [5, 2], [33, 2]]

CodePudding user response:

You need to have the add() method returning a Sum object for this to occur.

Here is a minimal example. (I named the class A because sum is a Python function and it is better not to confuse the two. )

class A:
    def __init__(self, n=0):
        self.value = n
        
    def __repr__(self):
        return str(self.value)
        
    def add(self, a_list):
        self.value  = sum(a_list)
        return self


x = A()
print(x)

x.add([3, 3])
print(x)

x.add([10,10]).add([1,1,1])
print(x)

Output:

0
6
29
  • Related