Skip to content

Commit f6a13d1

Browse files
committed
update 198-200
2 parents efdf23c + 44f7fda commit f6a13d1

File tree

1 file changed

+26
-13
lines changed

1 file changed

+26
-13
lines changed

README.md

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -459,45 +459,53 @@ def singleton(cls):
459459
instances[cls] = cls(*args, **kwargs)
460460
return instances[cls]
461461
return wrapper
462+
463+
462464
@singleton
463465
class Foo(object):
464466
pass
465467
foo1 = Foo()
466468
foo2 = Foo()
467-
print foo1 is foo2 #True
469+
print(foo1 is foo2) # True
468470
```
469471
第二种方法:使用基类
470472
New 是真正创建实例对象的方法,所以重写基类的new 方法,以此保证创建对象的时候只生成一个实例
471473
```python
472474
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)
476478
return cls._instance
477479

480+
478481
class Foo(Singleton):
479482
pass
480483

481484
foo1 = Foo()
482485
foo2 = Foo()
483486

484-
print foo1 is foo2 #True
487+
print(foo1 is foo2) # True
485488
```
486489
第三种方法:元类,元类是用于创建类对象的类,类对象创建实例对象时一定要调用call方法,因此在调用call时候保证始终只创建一个实例即可,type是python的元类
487490
```python
488491
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)
492495
return cls._instance
493-
```
494-
```python
496+
497+
498+
# Python2
495499
class Foo(object):
496500
__metaclass__ = Singleton
497501

502+
# Python3
503+
class Foo(metaclass=Singleton):
504+
pass
505+
498506
foo1 = Foo()
499507
foo2 = Foo()
500-
print foo1 is foo2 #True
508+
print(foo1 is foo2) # True
501509

502510
```
503511
### 18.反转一个整数,例如-123 --> -321
@@ -867,8 +875,13 @@ def loop_merge_sort(l1,l2):
867875
else:
868876
tmp.append(l2[0])
869877
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
872885
```
873886
### 37.给定一个任意长度数组,实现一个函数
874887
让所有奇数都在偶数前面,而且奇数升序排列,偶数降序排序,如字符串'1982376455',变成'1355798642'

0 commit comments

Comments
 (0)