python 老式类old style class和新式类new style class,类的单例模式

老式类old style class

class OldStyleClass():
    def __init__(self, a):
        self.a = a


新式类new style class

class NewStyleClass(object):
    def __init__(self, a):
        self.a = a

class OtherNewStyleClass(NewStyleClass):
    def __init__(self, a):
        super(OtherNewStyleClass, self).__init__(a)

新式类继承自object或者其他新式类。新式类可以使用super函数,而且比老式类多了一些特殊方法,比如__new__方法。

__new__方法是一个静态方法,你不需要通过staticmethod来特意指定,python解释器会自动判断。当你执行C(*args, **kwargs)时,

python的内部操作是先执行C.__new__(C,*args,**kwargs),比如new方法返回的结果叫ret,python会判断ret是否是C的实例,如果

是C的实例就执行C.__init__(ret,*args,**kwargs),通过init方法来初始化实例。

 

#c = C(10)  等价于  
c = C.__new__(C,10)
if isinstance(c, C): C.__init__(c, 10)

单例模式

class singleton(object):
    __instance = None
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = object.__new__(cls, *args, **kwargs)
        return cls.__instance
            
class C(singleton):
    pass
            
if __name__ == "__main__":
    c = C()
    c.a = 'a'
    print c.a
    c = C()
    #如果不继承singleton,将抛出异常:AttributeError: 'C' object has no attribute 'a'
    print c.a





 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值