运行PyCon2015的Python Super示例代码遇TypeError:缺少self参数
问题:调用父类实例方法时触发TypeError错误
我正在学习Raymond Hettinger在YouTube上的PyCon 2015演讲《Raymond Hettinger - Super considered super! - PyCon 2015》,输入了他用Python3.5演示的第一个示例代码pizza.py:
class DoughFactory(object): def get_dough(self): return 'insecticide treated wheat dough' class Pizza(DoughFactory): def order_pizza(self, *toppings): print('Getting Dough') dough = DoughFactory.get_dough() print('Making pie with %s' % dough) for topping in toppings: print('Adding: %s' % topping) if __name__ == "__main__": Pizza().order_pizza("pepperoni", "Bell Pepper")
使用Python3.5运行时出现以下报错,且在Python3.9环境及两台不同电脑上测试结果一致:
Getting Dough Traceback (most recent call last): File "pizza.py", line 18, in <module> Pizza().order_pizza("pepperoni", "Bell Pepper") File "pizza.py", line 11, in order_pizza dough = DoughFactory.get_dough() TypeError: get_dough() missing 1 required positional argument: 'self'
问题原因
get_dough是实例方法,定义时第一个参数为self,调用时需要自动传入当前实例对象。直接通过DoughFactory.get_dough()调用属于未绑定方法调用,没有传递实例参数,因此触发TypeError。
修复方案
有两种可靠的修复方式:
通过当前实例调用父类方法(推荐)
将dough = DoughFactory.get_dough()改为dough = self.get_dough()。由于Pizza继承自DoughFactory,实例会自动向上查找父类的方法,并传递self参数。
修改后的完整代码:class DoughFactory(object): def get_dough(self): return 'insecticide treated wheat dough' class Pizza(DoughFactory): def order_pizza(self, *toppings): print('Getting Dough') dough = self.get_dough() print('Making pie with %s' % dough) for topping in toppings: print('Adding: %s' % topping) if __name__ == "__main__": Pizza().order_pizza("pepperoni", "Bell Pepper")显式传递当前实例参数
将dough = DoughFactory.get_dough()改为dough = DoughFactory.get_dough(self),手动把当前Pizza实例作为参数传给父类的get_dough方法。
修复后运行结果
执行修改后的代码会输出:
Getting Dough Making pie with insecticide treated wheat dough Adding: pepperoni Adding: Bell Pepper
内容的提问来源于stack exchange,提问作者Questaware
相关产品推荐
相关产品推荐

