当我将属性歌词设置为lyrics_bday时,代码正常工作,在lyric_bulls或lyrics_tamasha的情况下,它会给出NameError。为什么会这样?
class Song(object):
def __init__(self, lyrics):
#self.lyrics is the instance while lyrics is the attribute
self.lyrics = lyrics_bday
def sing_me_a_song(self):
for line in self.lyrics:
print line
lyrics_bday = ["\n Happy Birthday to you", "\n I dont want to get sued", "\n So I'll stop here"]
happy_bday = Song(lyrics_bday) #passing the variable to class
lyrics_bulls = ["\n They rally around the family", "\n With pockets full of shells"]
bulls_on_parade = Song(lyrics_bulls)
lyrics_tamasha = ["\n Pal bhar sambhal jao", "\ndil ko kaise samjhaun", "\nAgar tum sath ho"]
agar_tum_sath_ho = Song(lyrics_tamasha)
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
答案 0 :(得分:0)
不确定您要在const groupByArray = (array1, array2) => {
const array2Set = new Set(array2);
return array1.reduce((r, s) => {
if(!r[r.length - 1] || array2Set.has(s)) {
r.push([]);
}
r[r.length - 1].push(s);
return r;
}, [])
};
const array1 = ["str1", "str2", "str3", "str4", "str5", "str6"];
console.log(groupByArray(array1, ["str2","str5"]));
console.log(groupByArray(array1, ["str2","str3"]));
中做什么,但截至目前,您的代码仅包含为歌词分配值;
在__init__
,您要将__init__
分配给lyrics_bday
,并且您将参数设为self.lyrics
,因此您需要使用lyrics
但是如果你正在调用函数那么为什么不在其中传递参数呢?见下面的代码示例:
self.lyrics = lyrics
输出:
class Song(object):
def __init__(self, **kwargs):
# ... include your desire code here
self.default_lyrics = ["*-"*10,"DEMO","lyrics..........","*-"*10]
def sing_me_a_song(self, lyrics=None):
if not lyrics:
lyrics = self.default_lyrics
for line in lyrics:
print(line)
song_object = Song()
lyrics_bday = ["\n Happy Birthday to you", "\n I dont want to get sued", "\n So I'll stop here"]
lyrics_bulls = ["\n They rally around the family", "\n With pockets full of shells"]
lyrics_tamasha = ["\n Pal bhar sambhal jao", "\ndil ko kaise samjhaun", "\nAgar tum sath ho"]
song_object.sing_me_a_song(lyrics_bday)
song_object.sing_me_a_song(lyrics_bulls)
song_object.sing_me_a_song()
你可以看到你不需要每次都创建类对象;只需在必要时传递参数,并考虑 Happy Birthday to you
I dont want to get sued
So I'll stop here
They rally around the family
With pockets full of shells
*-*-*-*-*-*-*-*-*-*-
DEMO
lyrics..........
*-*-*-*-*-*-*-*-*-*-
如果没有歌词传递给函数,你可以使用预定义的歌词值进行打印。