zoukankan      html  css  js  c++  java
  • 单例类与常见双下方法

    # 单例类 只能实例化一个对象的类叫做单例类
    
    class A:
        __ISINSTANCE = None
        def __new__(cls, *args, **kwargs):
            if not cls.__ISINSTANCE:
                cls.__ISINSTANCE = object.__new__(cls)
            return cls.__ISINSTANCE
        def __init__(self,name,age):
            self.name = name
            self.age = age
    
    a1  = A('ss',20)
    a2  = A('sss',30)
    print(a1)
    print(a2)
    # 这样A类就只能实例化一个对象
    class B:
        def __init__(self,name):
            self.name = name
        def __str__(self):
            return self.name
        
    b1 = B('sss')
    # 这个时候我们打印的结果就是str方法返回的结果
    print(b1)
    class B:
        def __init__(self, name):
            self.name = name
    
        def __str__(self):
                return '___%s' % self.name
        def __repr__(self):
            return self.name
    
    
    b1 = B('sss')
    # 当有str时打印str的结果否则打印repr的结果,repr支持%s 与%r ,当父类没有str或repr时在类链查找
    print(b1)
  • 相关阅读:
    洛谷-P2430 严酷的训练
    Hackthebox网络不稳定的解决方案
    解压
    谷歌地图API密钥未授权利用
    关于读取heapdump踩的一个小坑
    RECON
    最近思考
    go get
    Js跳转
    Session
  • 原文地址:https://www.cnblogs.com/tengx/p/11943798.html
Copyright © 2011-2022 走看看