繁体   English   中英

在 python 中传入自身数据

[英]passing in self data in python

您能否澄清一下self.add(x)下面的工作方式与self.data.append(x)的工作方式相同吗? 也就是说, self.add(x)怎么知道 append 到列表中,因为我们没有明确声明self.data.add(x) 当我们 state y.addtwice('cat')时,将'cat'添加到'self' ,而不是self.data

class Bag:
    def __init__(self):
        self.data=[]
    def add(self,x):
        self.data.append(x)
        return self.data
    def addtwice(self,x):
        self.add(x)
        self.add(x)
        return self.data

>>> y = Bag()
>>> y.add('dog')
['dog']
>>> y.addtwice('cat')
['dog', 'cat', 'cat']

因为addtwice调用定义在 self 上的方法,并且因为 self.data 是“可变类型”,所以 addtwice 对 add 的调用最终会附加 self.data 的值。 add ,依次调用 self.data.append

在计算机程序中调用 function 时,您可以将过程视为一系列替换,如下所示:

# -> means (substitution for)
# <= means "return"
y = Bag()
y.add('dog') -> 
     y.data.append(x) ->
         #(machine code)
     <= y.data
# at this point, at the command propmt, python will just print what was returned.
y.addtwice('cat')->
     y.add('cat')->
         y.data.append(x) ->
             #(machine code) 
         <= y.data
     #nothing cares about this return
     y.add('cat')->
         y.data.append(x) ->
             #(machine code)
         <= y.data
     #nothing cares about this return either
     <= y.data
# at this point, at the command propmt, python will just print what was returned.

不过,在任何这些情况下, self本身从未真正附加过。 self.data是。

self.add(x)调用实例方法add反过来调用self.data.append(x)

当我们 state y.addtwice('cat') 时,'cat' 被添加到 'self',而不是 self.data

这是不正确的。 cat实际上已添加到self.data中。 为什么你会认为它被添加到self

y.add('dog')Bag.add(y, 'dog')相同。 所以add确实是在做y.data.append('dog') ,习惯上用self这个名字代替。

y.addtwice('cat')Bag.addtwice(y, 'cat')相同。 所以addtwice真的是做y.add('cat')两次,这和做Bag.add(y, 'cat')两次是一样的。 所以addtwice实际上是在做y.data.append('cat')两次。

每个实例方法中的self只是一个自动添加的变量,指向调用它的实例,在本例中为y

让我们看看 class 包中的 function add(self, x)

当调用那个function时,其中一个参数是self,也就是object本身,在这种情况下,调用的是add function的同一个Bag实例。

因此,在 function add中,调用self.data.append(x)基本上就是调用 function append 到Bagdata列表中的元素x

同样的事情 function addtwice 通过调用 function add两次,将两个元素添加到 Bag 的data列表中。

这两个函数都返回data列表。

add(self, x)只是您要调用的 function 。

append是一个内置的 function 向列表中添加一个元素。

所以你添加 function 基本上使用 append 将你想要的元素添加到列表中并返回你命名的列表data

self.addtwice将调用 self.add 两次,因此将添加元素两次。

暂无
暂无

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

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