Uasthana Uasthana - 1 month ago 6
Python Question

How to pass argument implicitly in Python Class function

I was writing a python class and related functions. Suppose following is a class having a function that adds up all values of a numeric list and returns the sum

alist = [2,3,7,4,7]
MyClasss(object):
def __init__(self):
print("Roses are red")
def add_list(self,thelist):
j = 0
for i in the list:
j = j+i
return j

a = MyClasss()
print("sum is ",a.add_list(alist))


The above query will return the sum of the list just fine.

MY QUESTION IS:
Is it possible write this query or create a data object in which we do not have to pass the data object in the brackets instead write it something like this

alist.add_list()


and get the same results. Like we see different functions are available for different data types.
Any insights on this will be highly appreciated. Thanks

Answer

You can add it to __init__ on construction

class MyClasss(object):
    def __init__(self, theList):
        self.theList = theList
    def add_list(self):
        return sum(self.theList)

>>> a = MyClasss(alist)
>>> print("sum is ", a.add_list())
23
>>> print("sum is ", a.add_list())
23
Comments