python programming

python Singleton  

1.  Python __call__ special method practical example

instantiate a class: x = Foo() is really x = type(Foo).__call__(Foo), where __call__ is defined by the metaclass of Foo

2.  use call to implement Singleton

class _Singleton(type):
    """ A metaclass that creates a Singleton base class when called. """
    _instances = {}
    print("_instances")
    def __call__(cls, *args, **kwargs):
        ins = cls._instances.get(cls)
        print("class is:", cls, "instance is:", ins, args, kwargs)
        if not ins or (hasattr(ins, "_reset") and isinstance(ins, cls)
                and ins._reset()):
            cls._instances[cls] = super(
                    _Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Singleton(_Singleton('SingletonMeta', (object,), {})):
    print"Singleton"
    def __init__(self, *args, **kwargs):
        print("Singleton __init__", args, kwargs)

class Logger(Singleton):
    print"Logger"
    def __init__(self, *args, **kwargs):
        print("Logger __init__")
        print(args, kwargs)
    def _reset(self, *args, **kwargs):
        print("Logger _reset")
        print(args, kwargs)
        return True

print("Type is:", type(Logger))
print(dir(type(Logger)))
l = Logger("hello")
l = Logger("world")

Python classmethod()

__new__, __init__, __call__  

简述 __init__、__new__、__call__ 方法  

3.  Creating a singleton in Python

Method 2: A base class

class Singleton(object):
    _instance = None
    def __new__(class_, *args, **kwargs):
        if not isinstance(class_._instance, class_):
            class_._instance = object.__new__(class_, *args, **kwargs)
        return class_._instance

class MyClass(Singleton, BaseClass):
    pass

  

 decorators

1. decorators with parameters

from functools import wraps

def decorator(argument):
    def real_decorator(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            funny_stuff()
            something_with_argument(argument)
            retval = function(*args, **kwargs)
            more_funny_stuff()
            return retval
        return wrapper
    return real_decorator

  

2. Python class method decorator with self arguments

#/usr/bin/env python3
from functools import wraps

def wrapper(method):
    @wraps(method)
    def _impl(self, *method_args, **method_kwargs):
        method_output = method(self, *method_args, **method_kwargs)
        return method_output + "!"
    return _impl

class Foo:
    @wrapper
    def bar(self, word):
        return word

f = Foo()
result = f.bar("kitty")
print(result)

traceback

1. python3 org

2. Extract traceback info from an exception object

web development

我的爱家租房项目

 

exercise

二叉树遍历

  1 class T(object):
  2     def __init__(self, data=None, left=None, right=None):
  3        self.data = data
  4        self.left = left
  5        self.right = right
  6 
  7 #         1
  8 #       /   
  9 #      /     
 10 #     2      3
 11 #   /      /  
 12 #  4    5  6    7
 13 
 14 n4 = T(4)
 15 n5 = T(5)
 16 n6 = T(6)
 17 n7 = T(7)
 18 n2 = T(2, n4, n5)
 19 n3 = T(3, n6, n7)
 20 n1 = T(1, n2, n3)
 21 
 22 
 23 def preOrder(n):
 24     if not n:
 25         return
 26     print(n.data, end=" ")
 27     preOrder(n.left)
 28     preOrder(n.right)
 29 
 30 print("PreOrder:")
 31 preOrder(n1)
 32 
 33 def inOrder(n):
 34     if not n:
 35         return
 36     inOrder(n.left)
 37     print(n.data, end=" ")
 38     inOrder(n.right)
 39 
 40 print("
inOrder:")
 41 inOrder(n1)
 42 
 43 def PostOrder(n):
 44     if not n:
 45         return
 46     PostOrder(n.left)
 47     PostOrder(n.right)
 48     print(n.data, end=" ")
 49 
 50 print("
postOrder:")
 51 PostOrder(n1)
 52 print()
 53 
 54 print("*" * 20)
 55 
 56 def preOrderStack(n):
 57     if not n:
 58         return
 59     a = [n]
 60     cur = n
 61     while (a):
 62         cur = a.pop()
 63         print(cur.data, end=" ")
 64         if cur.right:
 65             a.append(cur.right)
 66         if cur.left:
 67             a.append(cur.left)
 68 
 69 print("PreOrderStack:")
 70 preOrderStack(n1)
 71 print()
 72 
 73 def inOrderStack(n):
 74     if not n:
 75         return
 76     a = []
 77     cur = n
 78     while (a or cur):
 79         while(cur):
 80             a.append(cur)
 81             cur = cur.left
 82         node = a.pop()
 83         print(node.data, end=" ")
 84         cur = node.right
 85 
 86 print("InOrderStack:")
 87 inOrderStack(n1)
 88 print()
 89 
 90 def postOrderStack(n):
 91     if not n:
 92         return
 93     a = [n]
 94     h = n
 95     cur = None
 96     while (a):
 97         c = a[-1]
 98         if (c.left and h !=c.left and h !=c.right):
 99             a.append(c.left)
100         elif (c.right and h != c.right):
101             a.append(c.right)
102         else:
103             node = a.pop()
104             print(node.data, end=" ")
105             h = c
106 
107 print("PostOrderStack:")
108 postOrderStack(n1)
109 print()
110 
111 
112 
113 def levelOrder(n):
114     if not n:
115         return
116     a = [n]
117     while (a):
118         c = a.pop(0)
119         print(c.data, end=" ")
120         if (c.left):
121             a.append(c.left)
122         if (c.right):
123             a.append(c.right)
124 
125 print("levelOrder:")
126 levelOrder(n1)
127 print()
View Code

 

原文地址:https://www.cnblogs.com/shaohef/p/11424646.html