不怎么用到的Python技巧(2)

2019-03-25  本文已影响0人  赤色要塞满了

重写__new__方法

>>> class CapStr(str):
    def __new__(cls, value):
        return super(CapStr, cls).__new__(cls, value.capitalize())  
>>> a = CapStr('abc')
>>> a
'Abc'

单例实现

>>> class Singleton():
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton, cls).__new__(cls)
        return cls.instance
>>> a = Singleton()
>>> b = Singleton()
>>> a is b
True

或者

>>> class Singleton():
    instance = None
    def __new__(cls):
        if not cls.instance:
            cls.instance = super(Singleton, cls).__new__(cls)
            # 也可以 cls.instance = object.__new__(cls) 
        return cls.instance

递归碾平多维数组

>>> a = [[1, 2, 3, [7, 8, 9]], [3, 4], [5, 6]]
>>> func = lambda x: [y for t in x for y in func(t)] if type(x) is list else [x]
>>> print(func(a))
[1, 2, 3, 7, 8, 9, 3, 4, 5, 6]

默认参数坑

Python的默认参数在编译阶段就创建了,可变对象容易坑

>>> def myfunc(num, lst=[]):
    lst.append(num)
    print(lst)
>>> myfunc(1)
[1]
>>> myfunc(2)
[1, 2]

排序可以传多个参数

>>> sorted([1, 2, 3, 0, -1, -2, -3], key=lambda x:(x<0, abs(x)))
[0, 1, 2, 3, -1, -2, -3]

上一篇下一篇

猜你喜欢

热点阅读