36 python 包装和授权

包装实例

# -*- coding: utf-8 -*-
# @Time    : 2018/7/12 17:08
# @Author  : Mr.c
# @File    : 包装标准类型.py
# @Software: PyCharm

class List(list):

    def append(self, object_str):
        if isinstance(object_str, str):
            super().append(object_str)  #python2 super(List, self)
        else:
            print('只能添加字符类型')
L1 = List('hello world')
print(L1)
L1.append('curry')
print(L1)
L1.append(123)

结果:

['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', 'curry']
只能添加字符类型

授权实例

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/7/12 17:48
# @Author  : Mr.c
# @File    : empower_test.py
# @Software: PyCharm

import time

class Open:

    def __init__(self, file_name, mode='r', encoding='utf-8'):
        self.file = open(file_name, mode, encoding=encoding)
        self.mode = mode
        self.encoding = encoding

    def __getattr__(self, item):
        return getattr(self.file, item)

    def write(self,content):
        t = time.strftime('%Y-%m-%d %X')
        self.file.write('%s %s' %(content, t))


open1 = Open('test.txt', 'w', encoding='utf8')
open1.write('harden is god')

结果:

test.txt

harden is god 2018-07-12 19:14:46

猜你喜欢

转载自www.cnblogs.com/jeavy/p/9301443.html
36
今日推荐