当前位置:  首页>> 技术小册>> Python合辑14-面向对象编程案例(下)

  1. class Element:
  2. def __init__(self, name, city, population):
  3. self.name = name
  4. self.city = city
  5. self.population = population
  6. def __str__(self):
  7. return str(self.__class__) + '\n' + '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))
  8. elem = Element('canada', 'tokyo', 321345)
  9. print(elem)

Output:

  1. name = canada
  2. city = tokyo
  3. population = 321345