通过继承解决代码重用的问题

通过继承解决代码重用的问题

Queue队列 : 先进先出.

class Queue:

    def __init__(self):

        self.l = []

    def put(self,item):

        self.l.append(item)

    def get(self):

        return self.l.pop(0) #从头开始弹出。

Stack堆栈:先进后出。

class Stack:

    def __init__(self):

        self.l = []

    def put(self,item):

        self.l.append(item)

    def get(self):

        return self.l.pop()

假设你希望一个类的多个对象之间 的某个属性 是各自的属性,而不是共同的属性。这个时候我们要把变量存储在对象的命名空间中,不能建立静态变量,

建立静态变量是所有的对象共同使用一个变量.

# 方法一

# class Foo:

#     def __init__(self):

#         self.l = []

#     def put(self, item):

#         self.l.append(item)

# class Queue(Foo):

#     def get(self):

#         return self.l.pop(0)

# class Stack(Foo):

#     def get(self):

#         return self.l.pop()

# 方法二:

# class Foo:

#     def __init__(self):

#         self.l = []

#     def put(self,item):

#         self.l.append(item)

#     def get(self):

#         return self.l.pop() if self.index else self.l.pop(0)

# class Queue(Foo):

#     def __init__(self):

#         self.index = 0

#         Foo.__init__(self)

# class Stack(Foo):

#     def __init__(self):

#         self.index = 1

#         Foo.__init__(self)

# 方法三

class Foo:

    def __init__(self):

        self.l = []

    def put(self, item):

        self.l.append(item)

    def get(self):

        return self.l.pop()

class Queue(Foo):

    def get(self):

        return self.l.pop(0)

class Stack(Foo):pass

Mypickle

import pickle

class Mypickle:

    def __init__(self,path):

        self.file = path

    def dump(self,obj):

        with open(self.file, 'ab') as f:

            pickle.dump(obj, f)

    #一种方法:

    # def load(self):

    #     with open(self.file,'rb') as f:

    #         while True:

    #             try:

    #                 yield pickle.load(f)

    #             except EOFError:

    #                 break

    #第二种方法:易理解,但如果文件过大,所有的值都要返回来,占据的空间就大。

    def load(self):

        l = []

        with open(self.file,'rb') as f:

            while True:

                try:

                    l.append(pickle.load(f))

                except EOFError:

                    break

        return l

# pic = Mypickle('pickle_file')

# s1 = Stack()

# s2 = Stack()

# s1.put(123)

# s1.put(456)

# pic.dump(s1)

# s2 = Stack()

# s2.put('aaa')

# s2.put(123)

# s2.put(456)

# pic.dump(s2)

 for i in pic.load():

     print(i.l)

原文地址:https://www.cnblogs.com/qqq789001/p/13391645.html