[英]In Python sharing class instance data and methods between threads but one specific variable
[英]instance methods sharing in python
1-是真的吗? 特定 class 的所有对象都有自己的数据成员但共享成员函数,memory 中仅存在一个副本?
2-以及为什么这段代码中init的地址相似:
class c:
def __init__(self,color):
print (f"id of self in __init__ on class is {id(self)}")
def test(self):
print("hello")
print (f"id of __init__ on class is {id(__init__)}")
a=c("red")
print(id(a.__init__))
print(id(a.test))
b=c("green")
b.test()
print(id(b.__init__))
print(id(b.test))
Output:
id of __init__ on class is 1672033309600
id of self in __init__ on class is 1672033251232
**1672028411200
1672028411200**
id of self in __init__ on class is 1672033249696
hello
**1672028411200
1672028411200**
是的,所有实例共享一个方法的相同代码。 通过具体实例引用方法时,会创建绑定方法object; 它包含对方法和实例的引用。 当调用此绑定方法时,它会调用方法 function 并将插入的实例作为第一个参数。
当您引用一个方法时,会创建一个新的绑定方法 object。 除非您将引用保存在变量中,否则 object 将立即被垃圾回收。 引用另一个方法将创建另一个绑定方法 object,它可以使用相同的地址。
将您的代码更改为
init = a.__init__
test = a.test
print(id(init))
print(id(test))
你会得到不同的ID。 将方法分配给变量可以防止 memory 被重用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.