Uasthana Uasthana - 1 year ago 53
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]
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.

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


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 Source

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())
>>> print("sum is ", a.add_list())