【发布时间】:2012-04-22 08:46:43
【问题描述】:
我在 Python 2.7 中遇到了类属性问题,设法找到了解决方案,但我不明白。
在以下人为设计的代码中,我希望每首歌曲都有自己的字典,其中包含所提到的一周中的几天的歌词。
class Song:
name = ""
artist = ""
# If I comment this line and uncomment the one in the constructor, it works right
week = {}
def set_monday( self, lyric ):
self.week[ "Monday" ] = lyric;
.
. # silly, I know
.
def set_friday( self, lyric ):
self.week[ "Friday" ] = lyric;
def show_week( self ):
print self.week
def __init__(self, name, artist):
self.name = name
self.artist = artist
# Uncomment the line below to fix this
# self.week = {}
def main():
songs = {}
friday_im_in_love = Song( "Friday I'm in Love", "the Cure" )
friday_im_in_love.set_monday( "Monday you can fall apart" )
friday_im_in_love.set_tuesday( "Tuesday can break my heart" )
friday_im_in_love.set_wednesday( "Wednesday can break my heart" )
friday_im_in_love.set_thursday( "Thursday doesn't even start" )
friday_im_in_love.set_friday( "Friday I'm in love" )
songs[ "Friday I'm in Love" ] = friday_im_in_love
manic_monday = Song( "Manic Monday", "the Bangles" )
manic_monday.set_monday( "Just another manic Monday" )
songs[ "Manic Monday" ] = manic_monday
for song in songs:
# This shows the correct name and artist
print songs[song].name + " by " + songs[song].artist
# The dictionary is incorrect, though.
songs[song].show_week()
if __name__ == '__main__':
main()
除了上面的代码运行时,输出是这样的:
Manic Monday by the Bangles
{'Friday': "Friday I'm in love", 'Tuesday': 'Tuesday can break my heart', 'Thursday': "Thursday doesn't even start", 'Wednesday': 'Wednesday can break my heart', 'Monday': 'Just another manic Monday'}
Friday I'm in Love by the Cure
{'Friday': "Friday I'm in love", 'Tuesday': 'Tuesday can break my heart', 'Thursday': "Thursday doesn't even start", 'Wednesday': 'Wednesday can break my heart', 'Monday': 'Just another manic Monday'}
这两个字典看起来都不像我期望的那样。所以回到代码,如果我在顶部注释week = {},并在构造函数中取消注释self.week={},字典就会按照我预期的方式出现。
Manic Monday by the Bangles
{'Monday': 'Just another manic Monday'}
Friday I'm in Love by the Cure
{'Friday': "Friday I'm in love", 'Tuesday': 'Tuesday can break my heart', 'Thursday': "Thursday doesn't even start", 'Wednesday': 'Wednesday can break my heart', 'Monday': 'Monday you can fall apart'}
这是为什么呢?
我意识到 name = "" 和 artist = "" 行(可能)是不必要的,但由于它们确实工作,我必须问:由于名称和艺术家字符串属性似乎“初始化”工作正常在构造函数之外;为什么没有周字典?
【问题讨论】:
-
“愚蠢”的例子没有错(尽管如果你真的想拥抱这种文化,你应该尝试使用基于更知名的 Monty Python 草图的例子——这是标准的)。不过,您似乎确实有一些挥之不去的分号炎。
-
嗨,迈克,这是来自 NU 的 Adam Forsyth,我们去年在 Norris 一起工作。最近怎么样? (我知道这不是一个社交网站,但我忍不住打招呼。)
-
我很容易承认分号问题——我仍然把大部分时间花在 PHP 上(而且我正在学习 Javascript)。适当地注意到了 Monty Python - 下次我会尽量记住这一点 :) 再次感谢 Karl。嘿,亚当!好久不见。
标签: python oop class dictionary