AttributeError' str'对象没有属性

时间:2017-12-03 17:20:35

标签: python

我是python的新手,我遇到了这个错误。我希望按名称命令在团队中打印动物的名字和出生年数。现在我一直在打印年份和名字,但没有订单。我想使用lambda而不是错误发生。你能帮帮我吗?

class Animal:
    def __init__(self, name):
        self.name = name

class Team:
    def __init__(self, name):
        self.name = name
        self.year_of_birth = year_of_birth
        self.members = []        

    def add_member(self, member):
        self.member = member
        self.members.append(team.member)

def print_team(team):
    list_members= []
    for member in team.members:
        list_members.append(member.name)
        list_members.append(member.year_of_birth)
        print('{} ({})'.format(member.name ,member.year_of_birth) )

    print (list_members)

    for memeber in list_members:
        sorted(list_members, key = lambda member: member.name)

    print (list_members)

team = Team('Wolves')
team.add_member(Animal('Josh', 2015))
team.add_member(Animal('Quinn', 2016))
team.add_member(Animal('Peter', 2010))
print_team(team)

行,在     已排序(memberlist,key = lambda成员:member.name) AttributeError:' str'对象没有属性' name'

1 个答案:

答案 0 :(得分:1)

这是另一种可能的解决方案:

要打印您创建的任何类的对象,必须将__str__()方法或__repr__()方法实现为对象的正式字符串表示形式。所以,这是修改后的Animal类:

class Animal:
    def __init__(self, name, year_of_birth):
        self.name = name
        self.year_of_birth = year_of_birth # Added this field because your created Animal objects had it in the example.

    def __str__(self):
        return self.name + " " + str(self.year_of_birth)

    def __repr__(self):
        return self.name + " " + str(self.year_of_birth)

接下来,我简化了您的add_member()方法,因为self.member = member没有理由:

def add_member(self, member):
        self.members.append(member)

接下来,我修改了你的print_team()函数:

def print_team(team):
    list_members= []
    for member in team.members:
        list_members.append(member)

    print("Unsorted: ")
    print (list_members)

    list_members.sort(key = lambda animal: animal.name)

    print("Sorted by name: ")
    print (list_members)

您只需在Animal列表中附加list_members类型的任何对象即可。之后,您可以使用sort()对列表进行排序,然后将其打印出来。以下代码:

team = Team('Wolves',2015)
team.add_member(Animal('Josh',2015))
team.add_member(Animal('Quinn',2145))
team.add_member(Animal('Peter',3000))
print_team(team)  

产生以下结果:

Unsorted: 
[Josh 2015, Quinn 2145, Peter 3000]
Sorted by name: 
[Josh 2015, Peter 3000, Quinn 2145]