b和c有什么区别?

时间:2016-07-31 04:58:08

标签: python python-3.x

请参阅以下代码:

class A:
def __init__(self, *args, **kwargs):
    self.l=[]
    #self.b=self.l.append

def foo(self):
    return 3


a=[]
b=A(a.append)
c=A()
b.foo()
print (b, c)
print (len(a))

对象bc之间有什么区别?具体来说a.append是什么意思。

3 个答案:

答案 0 :(得分:3)

bc是A类的不同实例。a.append是一种用于将值附加到列表的方法。

答案 1 :(得分:1)

b = A(a.append)在此处没有任何意义,因为A. init 不会对任何变量进行签名。所以答案是,b和c只是两个具有不同分配内存空间的对象。

答案 2 :(得分:0)

检查代码中提供的注释以获得解释:

class A:
    #Constructor to Class A, args contain list of formal arguments and kwargs contains object (dict) of keyward arguments
    #(4,5,None, test = "Hello", new = True) so args have [4,5,None] and kwargs have {"test":"Hello", "new" : True} 
    def __init__(self, *args, **kwargs):
       self.l=[]
       #self.b=self.l.append

    def foo(self):
       return 3


a=[]
#a is list and mutable data structure
b=A(a.append)
#a.append - append is method to list a to put values in list a like a.append(5), a.append(6) so list a is [5,6]. Here a.append provides info to memory location. 
#b is a variable contains reference to object A at mem location X   
c=A()
#c is a variable contains reference to object A at mem location Y
#b and c difference, Ideally both are reference to object A but located at diff locations and contains their own set of values/data. 
b.foo()
print (b, c)
print (len(a))