我试图在Python中学习OOP,但我对某些部分感到困惑。
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
def print_x(self):
print x
happy_bday = Song(["Happy birthday to you,",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They'll rally around the family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
x = Song(4)
x.print_x()
print_x()返回:
<__main__.Song object at 0x7f00459b4390>
而不是4.所以我尝试将x添加到__init__
和print_x
的参数,并将print x更改为在print_x
函数中打印self.x加上{{1 }} = x到init,但它返回:
self.x
老实说,我不知道这里出了什么问题。但任何帮助对我最终了解OOP都是非常有益的。
答案 0 :(得分:3)
这不是OOP问题,而是更多的范围问题。让我们来看一下非常简洁的版本。
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def print_x(self):
print x
从这里我们实例化x
(在本地范围内):
>>> x = Song(4)
现在,在我们做任何事情之前,让我们检查x
:
>>> print x.lyrics
4
原因是,当您致电Song(4)
时,价值4的位置确定为lyrics
。
当我们致电print_x
时:
>>> x.print_x()
<__main__.Song object at 0x7f00459b4390> # Or some other memory address
原因是Python知道的唯一x
是我们刚刚制作的本地x
。
当我们重新开始并制作y
时会发生什么:
>>> y = Song(4)
>>> print y.print_x ()
NameError: global name 'x' is not defined
打印时不存在x
,它会抛出异常。
答案 1 :(得分:0)
我认为你正在尝试
def __init__(self, lyrics, x):
self.lyrics = lyrics
self.x = x
...
def print_x(self):
print self.x
通过这种方式它将产生 TypeError:init()正好接受3个参数(给定2个)
您可以从中找到错误。
当您创建Song
实例时,如
happy_bday = Song(["Happy birthday to you,",
"I don't want to get sued",
"So I'll stop right there"])
您必须将x
的值传递给__init__()
。这就是错误显示的原因。这可以通过
happy_bday = Song(["Happy birthday to you,",
"I don't want to get sued",
"So I'll stop right there"],
'x-value')
或强>
设置x
def __init__(self, lyrics, x="default value"):
self.lyrics = lyrics
self.x = x