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

面向对象中的双下划线方法

  • __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)
  • __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()) # 抛出异常

猜你喜欢

转载自www.cnblogs.com/zhang-zi-yi/p/10755704.html