@@ -459,45 +459,53 @@ def singleton(cls):
459
459
instances[cls ] = cls (* args, ** kwargs)
460
460
return instances[cls ]
461
461
return wrapper
462
+
463
+
462
464
@singleton
463
465
class Foo (object ):
464
466
pass
465
467
foo1 = Foo()
466
468
foo2 = Foo()
467
- print foo1 is foo2 # True
469
+ print ( foo1 is foo2) # True
468
470
```
469
471
第二种方法:使用基类
470
472
New 是真正创建实例对象的方法,所以重写基类的new 方法,以此保证创建对象的时候只生成一个实例
471
473
``` python
472
474
class Singleton (object ):
473
- def __new__ (cls ,* args ,** kwargs ):
474
- if not hasattr (cls ,' _instance' ):
475
- cls ._instance = super (Singleton,cls ).__new__ (cls ,* args,** kwargs)
475
+ def __new__ (cls , * args , ** kwargs ):
476
+ if not hasattr (cls , ' _instance' ):
477
+ cls ._instance = super (Singleton, cls ).__new__ (cls , * args, ** kwargs)
476
478
return cls ._instance
477
479
480
+
478
481
class Foo (Singleton ):
479
482
pass
480
483
481
484
foo1 = Foo()
482
485
foo2 = Foo()
483
486
484
- print foo1 is foo2 # True
487
+ print ( foo1 is foo2) # True
485
488
```
486
489
第三种方法:元类,元类是用于创建类对象的类,类对象创建实例对象时一定要调用call方法,因此在调用call时候保证始终只创建一个实例即可,type是python的元类
487
490
``` python
488
491
class Singleton (type ):
489
- def __call__ (cls ,* args ,** kwargs ):
490
- if not hasattr (cls ,' _instance' ):
491
- cls ._instance = super (Singleton,cls ).__call__ (* args,** kwargs)
492
+ def __call__ (cls , * args , ** kwargs ):
493
+ if not hasattr (cls , ' _instance' ):
494
+ cls ._instance = super (Singleton, cls ).__call__ (* args, ** kwargs)
492
495
return cls ._instance
493
- ```
494
- ``` python
496
+
497
+
498
+ # Python2
495
499
class Foo (object ):
496
500
__metaclass__ = Singleton
497
501
502
+ # Python3
503
+ class Foo (metaclass = Singleton ):
504
+ pass
505
+
498
506
foo1 = Foo()
499
507
foo2 = Foo()
500
- print foo1 is foo2 # True
508
+ print ( foo1 is foo2) # True
501
509
502
510
```
503
511
### 18.反转一个整数,例如-123 --> -321
@@ -867,8 +875,13 @@ def loop_merge_sort(l1,l2):
867
875
else :
868
876
tmp.append(l2[0 ])
869
877
del l2[0 ]
870
-
871
-
878
+ while len (l1)> 0 :
879
+ tmp.append(l1[0 ])
880
+ del l1[0 ]
881
+ while len (l2)> 0 :
882
+ tmp.append(l2[0 ])
883
+ del l2[0 ]
884
+ return tmp
872
885
```
873
886
### 37.给定一个任意长度数组,实现一个函数
874
887
让所有奇数都在偶数前面,而且奇数升序排列,偶数降序排序,如字符串'1982376455',变成'1355798642'
0 commit comments