打印对象的默认实现
Default implementation of printing objects
这是我的代码:
class Person:
def __init__(self, name, age, favorite_foods):
self.name = name
self.age = age
self.favorite_foods = favorite_foods
def birth_year(self):
return 2017 - self.age
people = [Person('Bob', 47, ['Chicken'])
, Person('Jim', 26, ['Milk'])
, Person('Rick', 60, ['Tofu'])]
def __str__(self):
return 'Name: ' + self.name \
+ 'Age: ' + str(self.age) \
+ 'Favorite food: ' + str(self.favorite_foods[0])
age_sum = 0
year_sum = 0
for person in people:
age_sum = age_sum + person.age
year_sum = year_sum + person.birth_year()
print('The people polled in this census were: ')
print('The average age is: ' + str(age_sum / len(people)))
print('The average birth year is: ' + str(int(year_sum / len(people))))
print(person)
报错只显示内存位置?
The people polled in this census were:
The average age is: 44.333333333333336
The average birth year is: 1972
<__main__.Person object at 0x03DC6690>
如何让它显示正确的 container\list?
您的函数 __str__()
实际上不是您 class 定义的一部分。如果您将其定义移动到您的定义的一部分,它将按预期工作。换句话说——把它放在 之前 你定义数组 people
,并使用适当的缩进级别。
这是我的代码:
class Person:
def __init__(self, name, age, favorite_foods):
self.name = name
self.age = age
self.favorite_foods = favorite_foods
def birth_year(self):
return 2017 - self.age
people = [Person('Bob', 47, ['Chicken'])
, Person('Jim', 26, ['Milk'])
, Person('Rick', 60, ['Tofu'])]
def __str__(self):
return 'Name: ' + self.name \
+ 'Age: ' + str(self.age) \
+ 'Favorite food: ' + str(self.favorite_foods[0])
age_sum = 0
year_sum = 0
for person in people:
age_sum = age_sum + person.age
year_sum = year_sum + person.birth_year()
print('The people polled in this census were: ')
print('The average age is: ' + str(age_sum / len(people)))
print('The average birth year is: ' + str(int(year_sum / len(people))))
print(person)
报错只显示内存位置?
The people polled in this census were:
The average age is: 44.333333333333336
The average birth year is: 1972
<__main__.Person object at 0x03DC6690>
如何让它显示正确的 container\list?
您的函数 __str__()
实际上不是您 class 定义的一部分。如果您将其定义移动到您的定义的一部分,它将按预期工作。换句话说——把它放在 之前 你定义数组 people
,并使用适当的缩进级别。