zoukankan      html  css  js  c++  java
  • 内置函数(魔法方法)

    内置函数(魔法方法)

    凡是在类内部定义以——开头——结尾的方法,都是类的内置方法,也称之为魔法方法。

    类的内置方法,会在某种条件满足的情况之自动触发。

    __init__:在调用类时自动触发,调用该类的时候,内部会通过__new__产生一个新的对象。
    __new__:在调用new时自动触发,通过产生的对象自动调用__init__
    __getattr__:在对象.属性获取属性时,若属性没有时触发。
    __getattribute__:在对象.属性时,无论属性有没有都会触发。
    __setattr__:当对象.属性=属性值,添加或修改属性时触发。
    __call__:在调用对象+()时触发。
    __str__:打印对象时触发,注意,必须要有一个字符串返回值
    __getitme__:对象通过对象[key]获取值时触发
    __settime__:通过对象[key]设置值时触发

    单例模式:

    在确定类中的属性与方法不变时,需要反复调用,

    产生不同的对象,会产生不同的内存地址,造成资源的浪费。

    让所有的类实例化时,指向同一个内存地址,称之为单例模式。--》无论产生多个对象,都会指向单个实例。

    作用:节省内存空间

    单例模式:

    1.通过classmethod

    2.通过装饰器

    3.通过——new__实现

    4.通过导入模块

    5.通过元类实现

     

    栗子

    通过classmethod实现

    import settings
    class Mysql:
       __instance = None
       def __init__(self,host,port):
           self.host =host
           self.port =port
       @classmethod
       def singleton(cls,host,port):
           if not cls.__instance:
               obj = cls(host,port)
               cls.__instance = obj
           return cls.__instance
       def start_mysql(self):
           print('启动')
       def close(self):
           print('关闭')

    通过__new__实现
    class Abcd:
    __instance =None
    def __init__(self,name,age):
    self.name = name
    self.age = age
    def __new__(cls, *args,**kwargs):
    if not cls.__instance:
    #调用object.__new__产生一个空对象
    cls.__instance = object.__new__(cls)

    return cls.__instance
     

     

  • 相关阅读:
    numpy数组各种乘法
    python测试函数的使用时间
    dataframe 列名重新排序
    《图解设计模式》读书笔记5-1 composite模式
    《图解设计模式》读书笔记4-2 STRATEGY模式
    《图解设计模式》读书笔记4-1 Bridge模式
    《图解设计模式》读书笔记3-3 Builder模式
    《图解设计模式》读书笔记3-2 Prototype模式
    《图解设计模式》读书笔记3-1 Singleton模式
    《图解设计模式》读书笔记2-2 Factory Method模式
  • 原文地址:https://www.cnblogs.com/cyfdtz/p/11984735.html
Copyright © 2011-2022 走看看