对象属性为列表

时间:2013-06-23 20:57:24

标签: python python-3.x

没关系,似乎无论作者是什么,它都不承认它;它给出了同样的错误。 operator.attrgetter可能有问题吗?

提前致谢。

短,自包含,正确(可编译),例如:

import operator

class Source: 
    sources_count = 0 
    list_of_sources = [] 

    def __init__(self, title, author, year, publisher, city_of_publication, summary, type, tags): #basic attributes of Source class with addition to list_of_sources
        self.title = title
        self.author = author
        self.aSplit = author.split()
        self.authorFirst = self.aSplit[0]
        self.authorLast = self.aSplit[1]
        self.year = year
        self.publisher = publisher
        self.city_of_publication = city_of_publication
        self.summary = summary
        self.type = type
        self.tags = tags
        Source.sources_count += 1
        Source.list_of_sources.append(self)


s2 = Source("Hi", "Jacob Jenkins", "2013", "Publisher", "City", "Summary", "Print", "this, is, tag")
s1 = Source("Hoop", "Chelsea Chibbles", "2013", "Publisher", "City", "Summary", "Print", "this, is, tag")

print(s2.authorFirst)
print(s2.authorLast)
print(s1.authorFirst)
print(s1.authorLast)

key_last_name = operator.attrgetter("authorLast")
sorted_list = sorted(Source.list_of_sources, key=key_last_name)
print(sorted_list[0].authorLast, sorted_list[1].authorLast)

没有错误。我现在正在检查其余的代码。一旦我拿出这三个部分(类,方法和功能),它就可以正常工作。也许它确实与酸洗有关。

编辑:问题似乎已经解决了。我怀疑是我在对属性进行编辑之前腌制了文件,因此对象实际上没有所述属性,因为它们在属性存在之前被腌制。现在工作正常。

2 个答案:

答案 0 :(得分:2)

在构建列表后,浏览Source.list_of_sources,如下所示:

for src in Source.list_of_sources:
    if not hasattr(src, "authorLast"):
        print (src.aSplit)

查看是否有任何没有authorLast属性的Source实例。

修改

这是一种更安全的方式来分配名字/姓氏,以防你得到一个只有1个名字的作者:

self.asplit = self.author.split()
if len(self.asplit) == 1:
    self.asplit.append('')
self.authorFirstName = self.asplit[0]
self.authorLastName = self.asplit[-1]

如果作者是“F Scott Fitzgerald”之类的东西,给你一个名字“F”和一个姓氏“Fitzgerald”,这也有帮助。明确选择asplit [1]作为姓氏将错误地给出“Scott”。

答案 1 :(得分:1)

您的脚本中的其他位置必须有错误。 attrgetter 适用于字符串和列表:

>>> from operator import attrgetter
>>> class Book:
    def __init__(self, author):
        self.author_split = author.split()
        self.author_first = self.author_split[0]
        self.author_last = self.author_split[1]
    def __repr__(self):
        return 'Book(%r)' % ' '.join(self.author_split)


>>> books = Book('Stephen King'), Book('Dean Koontz')
>>> sorted(books, key=attrgetter('author_first'))
[Book('Dean Koontz'), Book('Stephen King')]
>>> sorted(books, key=attrgetter('author_last'))
[Book('Stephen King'), Book('Dean Koontz')]
>>> sorted(books, key=attrgetter('author_split'))
[Book('Dean Koontz'), Book('Stephen King')]