【问题标题】:instance methods sharing in pythonpython中的实例方法共享
【发布时间】:2021-06-24 13:48:17
【问题描述】:

1- 是真的吗? 特定类的所有对象都有自己的数据成员,但共享成员函数,内存中只存在一个副本?

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**

【问题讨论】:

    标签: python methods instance


    【解决方案1】:
    1. 是的,所有实例共享一个方法的相同代码。当你通过特定实例引用方法时,会创建一个绑定方法对象;它包含对方法和实例的引用。当调用此绑定方法时,它会调用方法函数,并将插入的实例作为第一个参数。

    2. 当您引用一个方法时,会创建一个新的绑定方法对象。除非您将引用保存在变量中,否则该对象将立即被垃圾收集。引用另一个方法会创建另一个绑定的方法对象,并且可以使用相同的地址。

    将代码更改为

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

    您将获得不同的 ID。将方法分配给变量可以防止内存被重用。

    【讨论】:

    猜你喜欢
    • 2012-12-05
    • 2021-10-02
    • 2010-10-21
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多