我已经在 python3.8 中实现了一个可迭代的类,在这篇实现该函数的帖子之后weakref()
,为了能够删除该类的元素,正如帖子接受的答案中所解释的那样。
问题是,如果我在函数中填充可迭代类,我将不再能够迭代其元素:
#! /usr/bin/env python3.8
import sys
import weakref
# from memory_profiler import profile
# IN = "/home/enrico/Dropbox/NY/asilo_variant/inputs/merged.idter_M.norm.PASS.filtered.head1k.VEPoutput.vcf"
a = [ "a", "b", "c", "d" ]
class VEPh_iterator(type):
def __iter__(self):
return self.classiter()
class VEPh:
'''
this stores VEP header and relative column numbers and chars
'''
__metaclass__ = VEPh_iterator
by_id = {}
def __init__(self, id, column_number):
self.id = id
# self.by_id[id] = self
self.by_id[id] = weakref.ref(self)
self.column_number = column_number
@classmethod
def classiter(cls):
# return iter(cls.by_id.values())
return (i for i in (i() for i in cls.by_id.values()) if i is not None)
def readVCF( ):
name_dict = {}
for i,s in enumerate(a) :
name_dict.update({ i : s })
name_dict[i] = VEPh( s, i )
if __name__ == "__main__" :
readVCF( )
for v in VEPh.classiter():
print( " - " + v.id + " : " + str(v.column_number) )
调用它有一个空的 OUT:
python3.8 /home/enrico/Dropbox/NY/asilo_variant/asilo_variant.stackoverflow.py
### NO STDOUT
如果修改删除weakref()
它有效:
#! /usr/bin/env python3.8
import sys
import weakref
# from memory_profiler import profile
# IN = "/home/enrico/Dropbox/NY/asilo_variant/inputs/merged.idter_M.norm.PASS.filtered.head1k.VEPoutput.vcf"
a = [ "a", "b", "c", "d" ]
class VEPh_iterator(type):
def __iter__(self):
return self.classiter()
class VEPh:
'''
this stores VEP header and relative column numbers and chars
'''
__metaclass__ = VEPh_iterator
by_id = {}
def __init__(self, id, column_number):
self.id = id
self.by_id[id] = self
# self.by_id[id] = weakref.ref(self)
self.column_number = column_number
@classmethod
def classiter(cls):
return iter(cls.by_id.values())
# return (i for i in (i() for i in cls.by_id.values()) if i is not None)
def readVCF( ):
name_dict = {}
for i,s in enumerate(a) :
name_dict.update({ i : s })
name_dict[i] = VEPh( s, i )
if __name__ == "__main__" :
readVCF( )
for v in VEPh.classiter():
print( " - " + v.id + " : " + str(v.column_number) )
称它有效:
python3.8 /home/enrico/Dropbox/NY/asilo_variant/asilo_variant.stackoverflow.py
- a : 0
- b : 1
- c : 2
- d : 3
我想问题是weakref()
函数之间以某种方式丢失了,但是我怎样才能让它可以被外部函数调用呢?