为什么我必须将x的歌词传递为4而不是两个字符串?我终于理解了参数以及如何满足它们,但我不明白为什么我必须将x的歌词传递给除了内存地址之外的其他内容,这与bulls_on_parade和happy_bday不同。
class Song():
def __init__(self, lyrics, x):
self.lyrics = lyrics
#self.x = x
def sing_me_a_song(self):
for line in self.lyrics:
print line
def print_x(self):
print x.lyrics
happy_bday = Song(["Happy birthday to you,",
"I don't want to get sued",
"So I'll stop right there"], 'x-value')
bulls_on_parade = Song(["They'll rally around the family",
"With pockets full of shells"], 'x-value')
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
def lyrics(args):
pass
x = Song(lyrics= 4, x = lyrics)
x.print_x()
答案 0 :(得分:2)
在此代码段中,您将全局名称lyrics
定义为函数。
将lyrics
作为x = lyrics
传递给x
的对象构造函数会将函数的地址传递给它(这不完全正确,但现在它会这样做)作为x
参数。
lyrics = 4
是不同的,因为Python区分函数调用参数名和变量名。
def lyrics(args):
pass
x = Song(lyrics= 4, x = lyrics)
事实上,如果在您的代码中执行此操作:
x = Song(lyrics=lyrics)
print x.lyrics
你会看到这样的事情:
<function lyrics at 0x107b9d1b8>