经典面试题

# 8. 练习题
info = [
    {'id': 1, 'name': '金鑫', 'pid': None},
    {'id': 2, 'name': '女神', 'pid': None},
    {'id': 3, 'name': '文州', 'pid': 1},
    {'id': 4, 'name': '高鑫', 'pid': 3},
    {'id': 5, 'name': '于超', 'pid': 2},
    {'id': 6, 'name': '袁浩', 'pid': 4},
]

info_dict = {}
for item in info:
    # print(item)
    item['children'] = []
    info_dict[item['id']] = item
print(info_dict)

result = []
for k,v in info_dict.items():
    pid = v.get('pid')
    if not pid:
        result.append(v)
        continue
    info_dict[pid]['children'].append(v)

print(result)

"""
children的pid对应前面的id值
result = [
    {
        'id': 1,
        'name': '金鑫',
        'pid': None,
        'children': [
            {'id': 3, 'name': '文州', 'pid': 1,
             'children': [{'id': 4, 'name': '高鑫', 'pid': 3, 'children': [{'id': 6, 'name': '袁浩', 'pid': 4}, ]}, ]},
        ]
    },
    {
        'id': 2,
        'name': '女神',
        'pid': None,
        'children': [
            {'id': 5, 'name': '于超', 'pid': 2},
        ]
    },
]
"""
#对象和对象相加
class Foo(object):
    def __init__(self,num):
        self.num = num
    def __add__(self, other):
        return self.num + other.a1

class Bar(object):
    def __init__(self,a1):
        self.a1 = a1

obj1 = Foo(9)
obj2 = Bar(11)

result = obj1 + obj2 #
print(result)
#手写单例模式
# 11. 手写单例模式
import time
import threading
class Singleton(object):
    lock = threading.RLock()
    instance = None

    def __new__(cls, *args, **kwargs):
        if cls.instance:
            return cls.instance
        with cls.lock:
            if not cls.instance:
                cls.instance = super().__new__(cls)
            return cls.instance

def task(arg):
    obj = Singleton()
    print(obj)
for i in range(10):
    t = threading.Thread(target=task,args=(i,))
    t.start()
time.sleep(100)

obj = Singleton()
# 13. 面向对象上下文管理 *****

class Foo(object):

    def __enter__(self):
        print('进入')
        return 666

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('退出')


obj = Foo()

with obj as x1:
    print(x1)
    print('操作中...')
# 14. 自己通过面向对象实现一个“栈”

class Stack(object):

    def __init__(self):
        self.container = []

    def push(self, value):
        """
        向栈插入数据
        :param value:
        :return:
        """
        self.container.append(value)

    def pop(self):
        """
        从栈中取走数据
        :return:
        """
        return self.container.pop()

 

posted @ 2019-02-26 22:18  从入门到出师  阅读(189)  评论(0编辑  收藏  举报