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)
  • 相关阅读:
    NYOJ 10 skiing DFS+DP
    51nod 1270 数组的最大代价
    HDU 4635 Strongly connected
    HDU 4612 Warm up
    POJ 3177 Redundant Paths
    HDU 1629 迷宫城堡
    uva 796
    uva 315
    POJ 3180 The Cow Prom
    POJ 1236 Network of Schools
  • 原文地址:https://www.cnblogs.com/tengx/p/11943798.html
Copyright © 2011-2022 走看看