zoukankan      html  css  js  c++  java
  • python 继承机制(子类化内置类型)

    1. 如果想实现与某个内置类型具有类似行为的类时,最好的方法就是将这个内置类型子类化。

    2. 内置类型子类化,其实就是自定义一个新类,使其继承有类似行为的内置类,通过重定义这个新类实现指定的功能。

    class newDictError(ValueError):
        '''如果向newDict添加重复值,则引发此异常'''
        
    class newDict(dict):
        '''不接受重复值的字典'''
        def __setitem__(self, key, value):
            if value in self.values():
                if((key in self and self[key] != value) or (key not in self)):
                    raise newDictError("这个值已经存在,并对应不同的键")
            super().__setitem__(key, value)
    demoDict = newDict()
    demoDict['key'] = 'value'
    demoDict['other_key'] = 'value2'
    print(demoDict)
    demoDict['other_key'] = 'value'
    print(demoDict)
    
    {'key': 'value', 'other_key': 'value2'}
    Traceback (most recent call last):
    
      File "C:/Users/24724/.spyder-py3/temp.py", line 15, in <module>
        demoDict['other_key'] = 'value'
    
      File "C:/Users/24724/.spyder-py3/temp.py", line 9, in __setitem__
        raise newDictError("这个值已经存在,并对应不同的键")
    
    newDictError: 这个值已经存在,并对应不同的键
    

    其实很多类都是对python内置类的部分实现,它们作为子类的速度更快,代码更整洁。

    对list进行子类化,实例代码如下:

    class myList(list):
        def __init__(self, name):
            self.name = name
        def dir(self, nesting = 0):
            offset = " " * nesting
            print("%s%s" % (offset, self.name))
            
            for element in self:
                if hasattr(element, 'dir'):
                    element.dir(nesting + 1)
                else:
                    print("%s%s" % (offset, element))
    demoList = myList('三打白骨精')
    demoList.append('真假孙悟空')
    print(demoList.dir())
    
    三打白骨精
    真假孙悟空
    None
    
  • 相关阅读:
    Map
    Enumeration输出
    iterator的基本用法
    Annotation整合工厂设计模式
    自定义Annotation
    Annotation
    动态代理设计模式
    静态代理设计模式
    自定义ClassLoader
    获取类的类对象的几种方式
  • 原文地址:https://www.cnblogs.com/xiaobaizzz/p/12229388.html
Copyright © 2011-2022 走看看