Bellow是我目前的代码,我对Python很陌生。我正在尝试创建一个Photo实例列表,其中每个Photo实例使用tups_list中每个元组的数据。并将该列表保存在变量photo_insts中。目前我没有收到错误,字面上,当我尝试运行该文件时,终端中没有发生任何事情。
photo_insts = []
tups_list = [("Portrait 2","Gordon Parks",["chicago", "society"]),("Children in School","Dorothea Lange",["children","school","1930s"]),("Airplanes","Margaret Bourke-White",["war","sky","landscape"])]
class Photo2(object):
def __init__(self, title_str, photo_by,tags_list):
self.title = title_str
self.artist = photo_by
self.tags = tags_list
for i in tups_list:
photo_tuple = (i[0],i[1],i[2])
photo_insts.append(photo_tuple)
print i
以下是运行以检查不同值的测试:
class Phototest(unittest.TestCase):
def test_photo_insts1(self):
self.assertEqual(type(photo_insts),type([]))
def test_photo_insts2(self):
self.assertEqual(type(photo_insts[0]),type(Photo("Photo2","Photo Student",["multiple","tags"])))
def test_photo_insts3(self):
self.assertEqual([x.title for x in photo_insts],["Portrait 2", "Children in School", "Airplanes"])
def test_photo_insts4(self):
self.assertEqual([x.artist for x in photo_insts],["Gordon Parks","Dorothea Lange","Margaret Bourke-White"])
def test_photo_insts5(self):
self.assertEqual([x.tags for x in photo_insts],[["chicago","society"],["children", "school","1930s"],["war","sky","landscape"]])
答案 0 :(得分:0)
我猜这是一个错字:
photo_tuple = (i[0],i[1],i[2])
=>
photo_tuple = Photo2 (i[0],i[1],i[2])
在创建实例__init__
时调用函数Photo2
。
如果你在函数Photo2 ()
中调用__init__
,那么你会得到一个递归!
=>代码应如下所示:
class Photo2(object):
def __init__(self, title_str, photo_by, tags_list):
self.title = title_str
self.artist = photo_by
self.tags = tags_list
# end class
tups_list = [
("Portrait 2","Gordon Parks",["chicago", "society"])
,("Children in School","Dorothea Lange",["children","school","1930s"])
,("Airplanes","Margaret Bourke-White",["war","sky","landscape"])
]
photo_insts = []
for i in tups_list :
photo_tuple = Photo2 (i[0],i[1],i[2])
photo_insts.append(photo_tuple)
print i[0]
for p in photo_insts :
print repr (p)
控制台输出:
Portrait 2
Children in School
Airplanes
<__main__.Photo2 object at 0xb7082cac>
<__main__.Photo2 object at 0xb7082ccc>
<__main__.Photo2 object at 0xb7082cec>