标签:
检查 object 是否为 class_or_type_or_tuple 的对象
class Foo(object): pass obj = Foo() if isinstance(obj,Foo): print(‘Yes‘) else: print(‘No‘)
检查 C 是否为 B 的子类
class B(object): pass class C(B): pass print(issubclass(C, B))
执行父类的方法
实例,有序字典
class MyDict(dict): def __init__(self): self.__li = [] super(MyDict,self).__init__() def __setitem__(self, key, value): self.__li.append(key) super(MyDict,self).__setitem__(key, value) def __str__(self): temp_list = [] for key in self.__li: temp_list.append("\‘%s\‘: %s" % (key,self.__getitem__(key))) temp_str ="{" + ",".join(temp_list) + "}" return temp_str obj = MyDict() obj[‘k1‘] = ‘v1‘ obj[‘k2‘] = ‘v2‘ print(obj)
异常处理的所有结构,至少包含 try...except...
try: # 逐行执行主代码段 print(123) except ValueError as ex: # 当检测到 ValueError 时执行 print(ex) except Exception as ex: # Exception 匹配所有一样 # 当检测到除 ValueError 之外的错误时执行 print(ex) else: # 当主代码块执行完成后执行 pass finally: # 无论主代码块是否有报错,都执行 pass
主动触发异常
try: raise Exception(‘主动错误一下‘) except Exception as e: print(e)
自定义异常
class MyException(Exception): def __init__(self, msg): self.message = msg def __str__(self): return self.message try: raise MyException("主动错一下自定义的错误") except MyException as e: print(e)
断言
# 当 assert 后面的表达式为 True 时不报错,否则报 AssertionError 错误 assert 1 == 1 assert 1 == 2
单利模式存在的目的是保证当前内存中仅存在单个实例,避免内存浪费
class ConnectPool(object): __pool = None def __init__(self): pass @staticmethod def get_pool(): if not ConnectPool.__pool: ConnectPool.__pool = ConnectPool() return ConnectPool.__pool obj1 = ConnectPool.get_pool() obj2 = ConnectPool.get_pool() print(obj1,obj2)
标签:
原文地址:http://www.cnblogs.com/wenchong/p/5874823.html