简体   繁体   English

python 中的实例方法共享

[英]instance methods sharing in python

1- is it true? 1-是真的吗? all the objects of a particular class have their own data members but share the member functions, for which only one copy in the memory exists?特定 class 的所有对象都有自己的数据成员但共享成员函数,memory 中仅存在一个副本?

2- and why the address of init in this code is similar: 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**
  1. Yes, all instances share the same code for a method.是的,所有实例共享一个方法的相同代码。 When you reference the method through a specific instance, a bound method object is created;通过具体实例引用方法时,会创建绑定方法object; it contains a reference to the method and the instance.它包含对方法和实例的引用。 When this bound method is called, it then calls the method function with the instance inserted as the first argument.当调用此绑定方法时,它会调用方法 function 并将插入的实例作为第一个参数。

  2. When you reference a method, a new bound method object is created.当您引用一个方法时,会创建一个新的绑定方法 object。 Unless you save the reference in a variable, the object will be garbage collected immediately.除非您将引用保存在变量中,否则 object 将立即被垃圾回收。 Referring to another method will create another bound method object, and it can use the same address.引用另一个方法将创建另一个绑定方法 object,它可以使用相同的地址。

Change your code to将您的代码更改为

init = a.__init__
test = a.test
print(id(init))
print(id(test))

and you'll get different IDs.你会得到不同的ID。 Assigning the methods to variables keeps the memory from being reused.将方法分配给变量可以防止 memory 被重用。

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

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