这篇文章是抄抄写写得来的,纯粹是这个编辑器比笔记的好太多,才在这儿写。
函数参数传递
对于变量(与对象相对的概念),其实,python函数参数传递可以理解为就是变量传值操作,用C++的方式理解,就是对void*赋值。如果这个变量的值不变,我们看似就是引用,如果这个变量的值改变,我们看着像是在赋值。
自己的理解:传递的值都会复制一份,如果是可变值,函数体内变量值变动时,指针指向的值会改,则看起来像是引用;如果是不可变值,函数体内变量值变动时,会重新赋值,则看起来像赋值。
global 与 nonlocal 比较
nonlocal
only works in py3
global
关键字用来在函数或其他局部作用域中使用全局变量。如果不修改全局变量,也可以不使用global
关键字
nonlocal
关键字用来在函数或其他作用域中使用外层(非全局)变量。
亲自动手试后,发现使用了 nonlocal 只会读闭包内的变量,可以隔着多层
init new
Use new when you need to control the creation of a new instance. Use init when you need to control initialization of a new instance.new is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class. In contrast, init doesn't return anything; it's only responsible for initializing the instance after it's been created. [3]
sf 上一哥们类比: new 看作为 alloc 步骤
A metaclass is just the class of a class. a metaclass's call method controls what happens when call a class. allows you to redefine the instance-creation mechanism from start to finish
class Singleton(type):
def __init__(self, *args, **kwargs):
super(Singleton, self).__init__(*args, **kwargs)
self.__instance = None
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super(Singleton, self).__call__(*args, **kwargs)
return self.__instance
__metaclass__ = Singleton
singleton [3]
def singleton(cls):
cls.__new_original__ = cls.__new__
@functools.wraps(cls.__new__)
def singleton_new(cls, *args, **kw):
it = cls.__dict__.get('__it__')
if it is not None:
return it
cls.__it__ = it = cls.__new_original__(cls, *args, **kw)
it.__init_original__(*args, **kw)
return it
cls.__new__ = singleton_new
cls.__init_original__ = cls.__init__
cls.__init__ = object.__init__
return cls
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。