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

 

转载于:https://www.cnblogs.com/shaohef/p/11424646.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值