打印对象的默认实现

时间:2017-01-22 04:24:41

标签: python self

这是我的代码:

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>

如何让它显示正确的容器\ list?

1 个答案:

答案 0 :(得分:2)

您的函数__str__()实际上并不是您的类定义的一部分。如果将其定义移动到定义的一部分,它将按预期工作。换句话说 - 在之前将定义为数组people,并使用适当的缩进级别。