python函数使用易错点_python 一些易错点整理

这篇文章是抄抄写写得来的,纯粹是这个编辑器比笔记的好太多,才在这儿写。

函数参数传递

对于变量(与对象相对的概念),其实,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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值