Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 数组';这不是第一次_Python_Python 2.7 - Fatal编程技术网

Python 数组';这不是第一次

Python 数组';这不是第一次,python,python-2.7,Python,Python 2.7,这是我的代码: class LangList(SGMLParser): is_span = "" langs = [] def start_span(self, attrs): for key, value in attrs: if key == 'class' and value == 'lang': self.is_span = 1 def end_span(self):

这是我的代码:

class LangList(SGMLParser):
    is_span = ""
    langs = []
    def start_span(self, attrs):
        for key, value in attrs:
            if key == 'class' and value == 'lang':
                self.is_span = 1
    def end_span(self):
        self.is_span = ""
    def handle_data(self, text):
        if self.is_span:
            self.langs.append(text)

...

for key in my_repositories.repositories.keys():
    print key

    each_repository_content = urllib2.urlopen(my_repositories.repositories[key]).read()

    my_repository = LangList()
    my_repository.feed(each_repository_content)

    print my_repository.langs
这是一个结果:

forensic_tools
['Python']
google
['Python', 'Python']
ListServices
['Python', 'Python', 'Java', 'Perl']
win32-assembly-projects
['Python', 'Python', 'Java', 'Perl', 'C']
...
我正在编写一个从github成员处获取存储库信息的应用程序


当我输出数组时,我发现数组不是初始的,存在重复元素。我如何解决这个问题

您的
langs
是一个类变量,而不是实例变量,因此它链接到类定义(因此在任何地方共享),而不是该类的任何特定实例

您可能想要更像:

class LangsList(sgmllib.SGMLParser):
    def __init__(self, *args, **kwargs):
        super(LangsList, self).__init__(*args, **kwargs)
        self.is_span = ""
        self.langs = []

您在初始化时创建实例变量的位置。

我是通过“数组尚未初始化”来猜测的,您的意思是“当我创建类的新实例时,
langs
保留以前实例添加的值”。如果希望
langs
每次都是新的,请在类的
\uuuu init\uuuu
方法中创建它,而不是直接在
行下创建它。您的说法是正确的。我执行类变量是不正确的。但是你的代码是错误的。我执行你的代码是错误的。它省略了super(LangsList,self)。\uuuuu init_uuu(*args,**kwargs),因此它不能成功地初始化。@TonyYang-oops,已修复。