Python b和c的区别是什么?
请参阅以下代码:Python b和c的区别是什么?,python,python-3.x,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)) 对象b和c之间有什么区别?具体来说,a.append的含义是什么 b和c是A类的不同实例。而A.append是用于将值追加到
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
的含义是什么 b
和c
是A类的不同实例。而A.append
是用于将值追加到列表中的方法。b=A(A.append)在这里没有任何意义,因为A.init没有对任何变量进行签名。所以答案是,b和c只是两个分配了不同内存空间的对象。检查代码中提供的注释以进行解释:
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))
什么
A.。\uuuu init\uuuu
对其参数没有任何作用,因此传入A.append
没有任何作用。A只是把它扔掉。它甚至没有很好的缩进,所以类A没有init