interview questions
- 传参数不能传 list / dict / set 等对象,为什么?(mutable / immutable)
- pass-by-value / pass-by-reference, all objects
- 哪些是 immutable 的 (bool, number, str, tuple),修改会发生什么?(TypeError, does not support item assignment)
- list / tuple 的区别 (mutable / immutable)
- super
- is / == 区别
- descriptor
- 单下划线和双下划线:
__foo__
内部用,_foo
私有变量,不能from module import *
;__foo
=> _classname__foo
iterable / iterator / generator / yield
- 将列表生成式中[]改成() 之后数据结构是否改变?(从列表变为生成器)
- Everything you can use “
for... in...
” on is aniterable
- Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly
- Stop
- yield
__metaclass__
/ __new__
/ __init__
- singleton
1 使用__new__
方法
#
class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kw)
return cls._instance
class MyClass(Singleton):
a = 1
2 共享属性 #
创建实例时把所有实例的__dict__
指向同一个字典,这样它们具有相同的属性和方法.
class Borg(object):
_state = {}
def __new__(cls, *args, **kw):
ob = super(Borg, cls).__new__(cls, *args, **kw)
ob.__dict__ = cls._state
return ob
class MyClass2(Borg):
a = 1
3 装饰器版本 #
def singleton(cls):
instances = {}
def getinstance(*args, **kw):
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return getinstance
@singleton
class MyClass:
...
4 import方法 #
作为python的模块是天然的单例模式
# mysingleton.py
class My_Singleton(object):
def foo(self):
pass
my_singleton = My_Singleton()
# to use
from mysingleton import my_singleton
my_singleton.foo()
scope: local => enclosing local => global => builtin
GIL: byte interpreter 上的锁
coroutine
copy
GC: reference counting, mark and sweep,
- generation collection
- 默认定义了三代对象集合,索引数越大,对象存活时间越长