Python中OOP的混淆
我正在尝试用Python学习OOP,但我对某些部分感到困惑Python中OOP的混淆,python,oop,Python,Oop,我正在尝试用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
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>
我真的不知道这里出了什么问题。但是,任何帮助都将对我最终理解OOP非常有益。我想你是在像这样尝试
def __init__(self, lyrics, x):
self.lyrics = lyrics
self.x = x
...
def print_x(self):
print self.x
通过这种方式,它将产生TypeError:init()正好接受3个参数(给定2个)
您可以从中找到错误。
当您创建歌曲
实例时
happy_bday = Song(["Happy birthday to you,",
"I don't want to get sued",
"So I'll stop right there"])
您必须将x
的值传递给\uuuu init\uuuu()
。这就是显示错误的原因。这可以通过
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
这不是一个OOP问题,而是一个范围问题。让我们检查一个非常精简的版本
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def print_x(self):
print x
从这里我们实例化x
(在本地范围内):
现在,在我们做任何事情之前,让我们检查一下x
:
>>> print x.lyrics
4
原因是调用歌曲(4)
时,值4根据其位置确定为歌词
当我们调用print\u x
:
>>> x.print_x()
<__main__.Song object at 0x7f00459b4390> # Or some other memory address
不存在要打印的x
,它会引发异常。您混淆了这些变量的作用域。局部变量和实例变量是完全不同的。在创建实例时,必须传递x
的值。类似于happy_bday=Song([“祝你生日快乐”,“我不想被起诉”,“所以我就到此为止”],“x-value”)
到底应该返回什么print_x
呢?尽管接受了-我想这里有一个打字错误。你说print y.lymps
会抛出namererror
,但我认为这没问题。我想你想说的是y.print\u x()
会抛出namererror
。
>>> print x.lyrics
4
>>> x.print_x()
<__main__.Song object at 0x7f00459b4390> # Or some other memory address
>>> y = Song(4)
>>> print y.print_x ()
NameError: global name 'x' is not defined