论python3下“多态”与“继承”中坑

一、背景:

近日切换到python3后,发现python3在多态处理上,有一些比较有意思的状况,特别记载,供你们参考。。。python

以廖老师的python3教程中的animal 和dog的继承一节的代码作例子,上代码先:ui

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Animal(object):
    def run1(self):
        print('Animal is running 1...')
    def run2(self):
        self.run1()
        print('Animal is running 2...')


class Cat(Animal):
    def run1(self,name):
        print('[%s] Cat is running1...' %name)
        
    def run2(self,name=""):
        super().run2()
        print('[%s] cat is running2...' %name)        


def run_twice(animal):
    animal.run1("1")
    animal.run2("2")


if __name__=='__main__':
    c = Cat()
    run_twice(c)

 

输出结果:spa

[1] Cat is running1...

报错信息以下:debug

 File "d:\python\tensf\clstest.py", line 28, in <module>
  run_twice(c)
 File "d:\python\tensf\clstest.py", line 23, in run_twice
  animal.run2("2")
 File "d:\python\tensf\clstest.py", line 17, in run2
  super().run2()
 File "d:\python\tensf\clstest.py", line 8, in run2
  self.run1()

builtins.TypeError: run1() missing 1 required positional argument: 'name'

二、分析缘由:

一、父类animal中run2()调用了run1()code

二、子类cat中覆盖了run1(),增长了name参数,并覆盖了run2(),一样增长了name参数,并调用父类animal中run2()blog

三、理想中的状态,父类的run2()应该是调用父类的run1(),实际倒是调用子类的run1(),因此致使参数匹配错误。继承

builtins.TypeError: run1() missing 1 required positional argument: 'name'

解决方案要分状况,就本例而言给name赋上默认值便可。


三、延伸

问题来源于本身写了configparser的扩展包,实现给get(),getint(),set()加默认值的方法,在python2中好用,移到python3中忽然很差用了,有点发懵。教程

不过仔细分析,仍是python3中configparser的get()有修改。ip

困扰了我接近一天,仍是基本功有问题,贴上我写的简单代码。

补充一点:python3下默认有configparser,无需额外用pip安装,并且大写改为了小写。utf-8

#coding=utf-8
'''
Date    :2016.10.8
Author  : joshua zou

Purpose : 
    configparser 的扩展类,增长默认值,兼容key不存在的状况。
Use exap: 
    import eConfig as eTax
    INICONFIG=eTax.eConfig()
    #读取配置文件中配置
    debuglevel = INICONFIG.get('default','debuglevel')
'''
try:
    from configparser import OrderedDict as _default_dict
except ImportError:
    # fallback for setup.py which hasn't yet built _collections
    _default_dict = dict
    
from configparser import RawConfigParser

class eConfig(RawConfigParser ):
    def __init__(self, defaults=None, dict_type=_default_dict, 
                allow_no_value=False):
        super().__init__(defaults, dict_type,allow_no_value)
        
    def get(self, section, option, default='',**kwargs):
        try :
            sRet =  super().get(section, option,**kwargs)
        except:
            sRet = default 
        return sRet
    
    def getint(self, section, option,default=None,**kwargs):
        try :          
            sRet =  super().getint(section, option,**kwargs)
        except Exception as e :
            sRet = default 
        return sRet

    def getfloat(self, section, option,default=None,**kwargs):
        try :
            sRet = super().getfloat(section, option)
        except:
            sRet = default 
        return sRet

    def getboolean(self, section, option,default=None,**kwargs):
        try :
            sRet = super().getboolean(section, option)
        except:
            sRet = default 
        return sRet
    
    def set(self, section, option,value):
        if not super().has_section(section):
            sRet =  super().add_section(section)
        sRet = super().set(section, option, value)    
        return sRet    
    
if __name__ == "__main__":
    #读取配置
    filename = r'zhbook.ini'
    sf=eConfig()
    sf.read(filename)
    
    print (sf.get('name', 'lastchp','1'))
    print (sf.getint('name', 'lastchp',0))
    print (sf.get('default', 'taskcount1', '1'))
    print (sf.get('default', 'taskcount1'))
    print (sf.getint('default', 'taskcount1'))
    print (sf.getboolean('default', 'taskcount1'))
    print (sf.getfloat('default', 'taskcount1'))
    print (sf.set('default2', 'taskcount1',u'2222'))
    
    #保存配置
    fp = open(filename,"w")
    sf.write(fp)
    fp.close()
    print (sf.get('default', 'taskcount1'))
    sf.remove_option('default','taskcount1')
    fp = open(filename,"w")
    sf.write(fp)
    fp.close()
    
相关文章
相关标签/搜索