Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中OOP的混淆_Python_Oop - Fatal编程技术网

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

我正在尝试用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>

我真的不知道这里出了什么问题。但是,任何帮助都将对我最终理解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