请参阅以下代码:
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))
对象b
和c
之间有什么区别?具体来说a.append
是什么意思。
答案 0 :(得分:3)
b
和c
是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))