我在 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 = ""
andartist = ""
行(可能)是不必要的,但由于它们确实有效,我必须问:由于名称和艺术家字符串属性似乎在构造函数之外“初始化”工作正常;为什么没有周字典?