zoukankan      html  css  js  c++  java
  • Python 学习笔记 5.对象驻留

    转载自:http://www.xwy2.com/article.asp?id=109

    我们知道 C# 中使用字符串驻留(string interning)机制来提高系统性能,可在 Python 中非但字符串有驻留机制,连整数等也拥有同样的待遇。

    Code
    >>>>>> i = 1
    >>>>>> i2 = 1

    >>>>>>
    id(i)
    11229288

    >>>>>>
    id(i2)
    11229288

    >>>>>>

    甚至是类成员也同样如此。

    Code
    >>>>>> class MyClass:
    def __init__
    (self):
    self.x
    = 123



    >>>>>> a =
    MyClass()
    >>>>>> b =
    MyClass()
    >>>>>>
    id(a.x)
    11229808

    >>>>>>
    id(b.x)
    11229808

    继续一个复杂一点的。

    Code
    >>>>>> class MyClass1:
    i
    = 123

    def __init__
    (self):
    self.x
    = 1234



    >>>>>> class
    MyClass2:
    i
    = 123

    def __init__
    (self):
    self.x
    = 1234



    >>>>>>
    id(MyClass1.i)
    11229808

    >>>>>>
    id(MyClass2.i)
    11229808

    >>>>>>
    id(MyClass1().x)
    12893924

    >>>>>>
    id(MyClass2().x)
    13241836

    >>>>>>

    即便在不同类型中,也只有实例成员的地址不同。

    我们还可以使用如下方式查看引用计数的变化,这是否意味着 Python 将简单类型也分配到堆上?

    Code
    >>>>>> import sys
    >>>>>> a = 1

    >>>>>>
    sys.getrefcount(a)
    699

    >>>>>> b =
    a
    >>>>>>
    sys.getrefcount(a)
    700

    >>>>>> c = 1

    >>>>>>
    sys.getrefcount(c)
    701

    >>>>>>

    而在 C# 中,显然堆或栈上都不可能如此。

    Code
    unsafe
    {
    int i
    = 1
    ;
    int i2
    = 1
    ;

    int
    * p1 = &
    i;
    int
    * p2 = &
    i2;

    Console.WriteLine((int)p1);
    Console.WriteLine((int)p2);
    }
  • 相关阅读:
    yum提示Another app is currently holding the yum lock
    函数参数返回值作用域笔记
    递归内置函数笔记
    装饰器笔记
    函数笔记扩展
    集合笔记
    线程和进程
    函数笔记
    线程与进程的区别
    Ubuntu操作及各种命令笔记.txt
  • 原文地址:https://www.cnblogs.com/sislcb/p/1283927.html
Copyright © 2011-2022 走看看