了解引用计数和元类

时间:2019-02-14 15:28:10

标签: python reference python-2.x

我正在尝试使用元类做一些事情,但我不理解我的python代码的结果。

function new-ls {

param([Parameter(Position=0)]
[string]$Path,
[Parameter(Position=1)]
[string[]]$Includes)


$StrMatch = ($Path | sls -pattern "^(.*?){(.*?),(.*?)}(.*?)$" -allmatches).matches.groups.value
$NewPaths = @(($StrMatch[1] + $StrMatch[2] + $StrMatch[4]), ($StrMatch[1] + $StrMatch[3] + $StrMatch[4]))
ls $NewPaths -include $Includes -recurse

}

# Running the code

PS C:\temp> new-ls "c:\temp\{test1,test2}\*"


    Directory: C:\temp\test1\test1subdir


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        2/14/2019  10:29 AM             13 test1file.txt


    Directory: C:\temp\test2


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        2/14/2019  10:30 AM              6 test2file.log


PS C:\temp> new-ls "c:\temp\{test1,test2}\*" "*.txt"


    Directory: C:\temp\test1\test1subdir


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        2/14/2019  10:29 AM             13 test1file.txt

PS C:\temp> new-ls "c:\temp\{test1,test2}\*" "*.txt","*.log"


    Directory: C:\temp\test1\test1subdir


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        2/14/2019  10:29 AM             13 test1file.txt


    Directory: C:\temp\test2


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        2/14/2019  10:30 AM              6 test2file.log

我在import sys class Meta(type): a = None b = None def __call__(cls, *args, **kwargs): name = args[0] if getattr(cls, name) is None: setattr(cls, name, super(Meta, cls).__call__(*args, **kwargs)) return getattr(cls, name) class A: __metaclass__ = Meta def __init__(self, name, in_a = None): self.a = None if in_a: self.a = in_a a = A("a") print sys.getrefcount(a) - 2 # 1 b = A("b", a) print sys.getrefcount(a) - 2 # 2 b = None print sys.getrefcount(a) - 2 # 2? 上有两个引用,其中之一是a的属性。

当我删除引用b(或设置为b)时,None上的引用数仍为2。

现在,当我不使用元类时,它可以很好地工作:

a

您能解释一下区别吗?

1 个答案:

答案 0 :(得分:1)

在您的代码中,b也存储为A.b,因此仅将全局b设置为None不会触发该实例的收集-因为仍然存在对它的引用-因此引用计数保持不变。 IOW,您忘了检查b ;-)

上的引用计数

只需添加A.b = None,您就会看到refcount减少了。

请注意,它与元类无关(不确定您实际上要在这里做什么,但是可能有一个更简单/明显的解决方案)。