python 一些易错点整理

发布时间:2019-06-18 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了python 一些易错点整理脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

函数参数传递

Python的函数参数传递

对于变量(与对象相对的概念),其实,python函数参数传递可以理解为就是变量传值操作,用C++的方式理解,就是对void*赋值。如果这个变量的值不变,我们看似就是引用,如果这个变量的值改变,我们看着像是在赋值。

自己的理解:传递的值都会复制一份,如果是可变值,函数体内变量值变动时,指针指向的值会改,则看起来像是引用;如果是不可变值,函数体内变量值变动时,会重新赋值,则看起来像赋值。

global 与 nonlocal 比较

python中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

脚本宝典总结

以上是脚本宝典为你收集整理的python 一些易错点整理全部内容,希望文章能够帮你解决python 一些易错点整理所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。