Discuss / Python / 各位大佬这是在练习过程中遇到的错误,不晓得怎么改

各位大佬这是在练习过程中遇到的错误,不晓得怎么改

Topic source

class Student(object):

    def __init__(self,name,score):

        self.name=name

        self.score=score

    def print_score(self):

        print('%s:%s'%(self.name,self.score))

    bart=Student('huahua',69)

print_score(bart)

Bart simpson:59

bart.print_score()

AttributeError                            Traceback (most recent call last)
<ipython-input-64-e084fcad3a98> in <module>
----> 1 bart.print_score()

AttributeError: 'Student' object has no attribute 'print_score'

print_score(bart)

这句调用好像有问题,

print_score()是内部定义的方法,不是外部的函数,这样直接是调用外部函数的意思,但是外部并没有这样的函数

这句是可以输出结果的,结果是Bart simpson:59,但下面这句就输不出来,bart.print_score(),总是提示 'Student' object has no attribute 'print_score'

洛晨斯

#4 Created at ... [Delete] [Delete and Lock User]

廖老师是这么玩的,你应该是绕进去了,不妨重新看一遍讲解。

class Student(object):

    def __init__(self,name,score):

        self.name=name

        self.score=score

    def print_score(self):

        print("%s:%s"%(self.name,self.score))

bart=Student('huahua',69)

bart.print_score()

def print_score(std):

        print("%s:%s"%(std.name,std.score))

print_score(bart)

result:

huahua:69

huahua:69

老兄按照你的方法解决啦。可是想再进一步的问你一下,我发生错误的原因是什么呢?

In·too·deep

#6 Created at ... [Delete] [Delete and Lock User]

emmm~~同是新手,应该是你的这句    bart=Student('huahua',69)     位置不对,放到class里面了,删掉前面的空格就可以吧

mf734

#7 Created at ... [Delete] [Delete and Lock User]

也是新手,用自己的理解回答一下,如果错了请指正,欢迎讨论。

首先,你要搞懂外部函数和内部函数的区别。

以这章的print_score为例:

如果用普通的单独的外部函数(而不是用class内部的函数),那么我们就先定义一个**print_score(std)**的方法,再用 **print_score(bart) **去调用这个方法 。

内部函数(特指Student class的内部),我们希望只在Student里用,不给别的用,那我们需要一个专属于这个Student的print_score

注意:外部函数的print_score(std)“来者不拒”,但是能不能运行那就看你的输入能不能对的上;而Student的内部函数的print_score(self)接受的是这个self,即属于这个Student class的这个object。

你在你的程序中,有两个print_score的方法。你如果直接写print_score(bart),默认用的是外部的“来者不拒”函数。如果想用Student里面的那个函数,有两个方法:第一,用“Student.print_score(bart)”;第二,用bart.print_score()。为什么这俩方法可用不赘述,前面几章都有。

你的第二种方法出错,报错原因是Student里面没有print_score(),说明你没有定义进去。具体怎么回事,可能是你的缩进有问题,或者你新定义的还没有运行,就直接调用了。不管怎么样,你原本想要封装进Student这个class里去的内部函数没有封装进去。

解决方法可以根据错因来。我个人建议是,查一下缩进,然后重新运行一下整个程序。最好把内部函数和外部函数print出来的东西改一下(比如在外部函数上,print一个“这是个外部函数”,等等),这样你就知道自己调用的是内部还是外部函数、是不是自己想要调用的那一个了。

你调用

print_score(bart)

输出的是

Bart simpson:59

很明显你的bart并不是这个Student里的实例对象,而是你之前就定义好的了。

原因就在于你缩进错误把bart实例的创建写进了你新定义的Student类里,把bart变成了Student类的一个属性。

当然这是封装在Student里的,也就是它实际上是Student.bart。

然后你本来的外部的bart是你之前赋值好的一个Student类的对象,该Student类没有print_score 属性。(尽管你新写的Student覆盖了你原来的Student,但是曾经创建的实例对象已经保留下来了)

bart=Student('huahua',69)

前面缩进了,把空格删了就好了

意外缩进了


  • 1

Reply