如何列出类中的对象

时间:2017-05-04 02:50:26

标签: python list class object

我有一个班级

class movie:

 def __init__(self, title, year, release):
    self._title = title
    self._year = year
    self._release= release

 def getTitle(self):
    return self._title
 def getYear(self):
    return self._year
 def getRel(self):
    return self._release

 def setTitle(self, title):
    self._title = movie
 def setYear(self, year):
    self._year = movie
 def setRel(self, release):
    self._release = movie


 def __str__(self):
    outputString = "Title:" + str(self._title) + "Year:" + str(self._year) + "Production:" + str(self._release)
    return outputString

我想从这个

中创建一个列表
import movie

mfirst = movie.movie("The Shawshank Redemption", "1994", "Castle Rock Entertainment")
msecond = movie.movie("The Godfather", "1972", "Paramount Pictures")

有没有办法可以单独列出标题,年份和制作工作室? 我尝试了不同的方法,但继续收到类似[<movie.movie instance at 0x10117ecf8>]

的内容

1 个答案:

答案 0 :(得分:0)

您拥有用于获取值的setter和getter,因此我们可以利用它,并且对于您实例化的每个对象,您可以对所有对象应用统一查询。

在你的movie.py

class Movie:

 def __init__(self, title, year, release):
    self._title = title
    self._year = year
    self._release= release

 def getTitle(self):
    return self._title
 def getYear(self):
    return self._year
 def getRel(self):
    return self._release

 def setTitle(self, title):
    self._title = movie
 def setYear(self, year):
    self._year = movie
 def setRel(self, release):
    self._release = movie


 def __str__(self):
    outputString = "Title:" + str(self._title) + "Year:" + str(self._year) + "Production:" + str(self._release)
    return outputString

在另一个文件中,我们称之为my_movies.py

from movie import Movie

first_movie = Movie("The Shawshank Redemption", "1994", "Castle Rock Entertainment")

second_movie = Movie("The Godfather", "1972", "Paramount Pictures")

my_movies = [first_movie, second_movie]

titles = []
years = []
releases = []

for m in my_movies:
    titles.append(m.getTitle())
    years.append(m.getYear())
    releases.append(m.getRel())

print('\t'.join(titles))
print('\t'.join(years))
print('\t'.join(releases))