对象属性为Lis

2024-10-02 22:34:22 发布

您现在位置:Python中文网/ 问答频道 /正文

不管怎样,似乎不管作者是谁,它都无法识别;它给出了相同的错误。这辆车有什么问题吗接线员,是吗?你知道吗

提前谢谢。你知道吗

简短、完整、正确(可编译),示例:

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)

没有错误。我现在正在检查其余的代码。只要我把这三个部分(类、方法和函数)去掉,就可以很好地工作了。可能和腌制有关。你知道吗

编辑:问题似乎已经解决了。我的怀疑是,在编辑属性之前,我已经对文件进行了pickle处理,因此对象实际上没有说属性,因为它们是在属性存在之前进行pickle处理的。现在可以了。你知道吗


Tags: ofselfcitysourcetitlesummaryyearlist
2条回答

建立列表后,按以下方式浏览Source.list_of_sources

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

查看是否得到任何没有authorLast属性的源实例。你知道吗

编辑:

以下是一种更安全的方法来指定名/姓,以防您得到一个只有一个名字的作者:

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”。你知道吗

脚本中的其他地方一定有bug。对于字符串和列表,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')]

相关问题 更多 >