Attributeerror 'str' Object Has No Attribute
I am new to python and I get stuck in this error. I want to print names and years of birth of animals in team in an order by the name. Now I am keeping getting printing years and n
Solution 1:
Here is another possible solution:
In order to print an object of any class that you created, you must implement the __str__()
method or the __repr__()
method as an official string representation of your objects. So, here is the modified Animal
class:
classAnimal:
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)
Next thing, I simplified your add_member()
method because there was no reason for self.member = member
:
defadd_member(self, member):
self.members.append(member)
Next, I modified your print_team()
function like this:
defprint_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)
You can simply append any object of type Animal
in the list_members
list. After that, you can sort your list using sort()
and then print it. The code below:
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)
Produces the following result:
Unsorted:
[Josh2015, Quinn2145, Peter3000]
Sorted by name:
[Josh2015, Peter3000, Quinn2145]
Post a Comment for "Attributeerror 'str' Object Has No Attribute"