zoukankan      html  css  js  c++  java
  • 【转】python 调用super()初始化报错“TypeError: super() takes at least 1 argument”

    一、实验环境

    1.Windows7x64_SP1

    2.Anaconda2.5.0 + python2.7(anaconda集成,不需单独安装)

    二、实验步骤

    2.1 在python中有如下代码:

    class father():
      def __init__(self,age):
        self.age = age;
      def get_age(self):
        print(self.age);
    
    class son(father):
      def __init__(self,age):
        super().__init__(age);
        self.toy_number = 5;
      def get_toy_number(self):
        print(self.toy_number);
    
    myson = son(6)
    myson.get_age()
    myson.get_toy_number()

    运行时报错:“TypeError: super() takes at least 1 argument(0 given)”

    2.2 原因分析

    该方法调用super()为在python3中的方法,而此是在python2中运行的,在python3中运行将正常。

    在《python编程:从入门到实践》一书中介绍了若想在python2中运行需将 

    super().__init__(age)

    一句改为:

    super(son, self).__init__(age)

    但我按此方法改后,运行时报错:“TypeError: super() argument 1 must be type, not classobj”

    2.3 解决方式

    上网查询资料后,得知若想要在python2中运行成功,可以改为如下两种方法:

    方法一

    class father(object):
      def __init__(self,age):
        self.age = age;
      def get_age(self):
        print(self.age);
    
    class son(father):
      def __init__(self,age):
        super(son, self).__init__(age);
        self.toy_number = 5;
      def get_toy_number(self):
        print(self.toy_number);
    
    myson = son(6)
    myson.get_age()
    myson.get_toy_number()

    方法二

    class father():
      def __init__(self,age):
        self.age = age;
      def get_age(self):
        print(self.age);
    
    class son(father):
      def __init__(self,age):
        father.__init__(self,age);#注意此处参数含self
        self.toy_number = 5;
      def get_toy_number(self):
        print(self.toy_number);
    
    myson = son(6)
    myson.get_age()
    myson.get_toy_number()

    运行后都将得到正确答案:

    参考链接:https://stackoverflow.com/questions/9698614/super-raises-typeerror-must-be-type-not-classobj-for-new-style-class
    原文请参考:https://blog.csdn.net/u010812071/article/details/76038833

  • 相关阅读:
    深入MVC模式概念
    Asp.NET MVC and Asp.NET WebForms Features
    JavaScript实现简单进度条
    数据分页技术(学习笔记)
    sql行列转换<转>
    全自动静态网页生成器(三)——发布第一个可用版本
    ASP.NET AJAX进度条
    不能远程访问Win7系统上的Sql 2005数据库
    水印及缩略图的C#实现
    无任何网络提供程序接受指定的网络路径解决方法
  • 原文地址:https://www.cnblogs.com/hester/p/11311208.html
Copyright © 2011-2022 走看看