Discuss / Python / 问题:

问题:

Topic source

神月宗

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

为什么在调用run_twice()的时候需要将基类的run()加上self呢? 例如:

-- coding: utf-8 --

class Animal(object): def run(self):#为什么这需要加上一个self,是不是代表这个类本身去执行呢?

#不加的话就会报错
    print 'Animal is running...'

def run_twice(animal): animal.run() animal.run()

run_twice(Animal())

#running output:

#Animal is running...

#Animal is running...

云澄

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

这个self代表类的实例,上面教程说的很清楚,报错的原因是实例的方法在调用时,解释器会默认把实例变量传进去当做一个参数,但你方法里又没写self参数,所以会报错


  • 1

Reply