简体   繁体   English

如何在Python类函数中隐式传递参数

[英]How to pass argument implicitly in Python Class function

I was writing a python class and related functions. 我正在编写一个python类和相关函数。 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 谢谢

You can add it to __init__ on construction 您可以在构造时将其添加到__init__

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

>>> a = MyClasss([2,3,7,4,7])
>>> print("sum is ", a.add_list())
23
>>> print("sum is ", a.add_list())
23

Another way to do this is create a partial function from functools.partial and call that: 另一种方法是从functools.partial创建一个局部函数,然后调用该函数:

>>> import functools as ft
>>> a = MyClasss()
>>> a.add_list = ft.partial(a.add_list, [2,3,7,4,7])
>>> a.add_list()
23

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM