面向对象中的双下划线方法 单例模式 实现一个栈

面向对象中的双下滑方法

  • __new__ 单例模式

    import threading
    
    class Singleton(object):
        _instance = None
        _lock = threading.RLock()
    
        def __new__(cls, *args, **kwargs):
            if cls._instance:
                return cls._instance
            with cls._lock:
                if not cls._instance:
                    cls._instance = super().__new__(cls, *args, **kwargs)
                return cls._instance
  • __setitem__ __getitem__ __delitem__ 可以使用 [ ] 赋值

    class Foo(object):
    
        def __setitem__(self, key, value):
            pass
    
        def __getitem__(self, item):
            pass
    
        def __delitem__(self, key):
            pass
    
    obj = Foo()
    
    obj['k1'] = 'value'  # 使用的是 __setitem__
    obj['k1']   #  使用的是 __getitem__
    del obj['k1']  #  使用的是 __delitem__
  • __enter__ __exit__ 可以使用 with 语句

    class Foo(object):
    
        def __enter__(self):
            print('进入')
            return 123
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            print('退出')
    
    obj = Foo()
    with obj as f:
        print(f)
    • 实现一个自定义 open
    class MyOpen(object):
    
        def __init__(self, file_path, mode='r', encoding='utf-8'):
            self.file_path = file_path
            self.mode = mode
            self.encoding = encoding
    
        def __enter__(self):
            self.f = open(file=self.file_path, mode=self.mode, encoding=self.encoding)
            return self.f
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            self.f.close()
    
    
    with MyOpen('a.txt', mode='w', encoding='utf-8') as f:
        f.write('写点什么啊 !')
  • __call__ 可以

    class Foo(object):
    
        def __call__(self, *args, **kwargs):
            return "value"
    obj = Foo()
    obj()  # value
    # flask源码入口
  • __iter__ __next__ 迭代器

    class Iterator(object):
      def __init__(self, data):
          self.data = data
          self.index = 0
    
      def __iter__(self):
          return self
    
      def __next__(self):
          if "__iter__" in dir(self.data):
              if self.index == len(self.data):
                  raise StopIteration
              else:
                  a = self.data[self.index]
                  self.index += 1
                  return a
          else:
              raise StopIteration
    for value in Iterator("22123"):
        print(value)

手写栈

class StackFullError(Exception):
    pass
class StackEmptyError(Exception):
    pass
class Stack(object):

    def __init__(self,size):
        self.size = size
        self.index = 0
        self.lis = []


    def push(self,obj):
        if self.index < self.size:
            self.lis.insert(self.index, obj)
            self.index += 1
        else:
            raise StackFullError("装满了")

    def pop(self):
        if self.index > 0:
            self.index -= 1
            return self.lis[self.index]
        else:
            raise StackEmptyError("取完了")

s = Stack(2)

s.push("value_1")
s.push("value_2")
s.push("value_3")
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop()) # 抛出异常

鸭子模型

class Foo(object):
    def xxxxx(self):
        pass
    
class Base(object):
    def xxxxx(self):
        pass

def func(arg):
    arg.xxxxx()
    
obj1 = Foo()
obj2 = Base()

func(obj1)
func(obj2)

转载于:https://www.cnblogs.com/zhang-zi-yi/p/10755704.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值