Tornado中的单例模式(Singleton)

本文探讨了Python中的单例模式,通过实例解析了@classmethod和@staticmethod的区别。阐述了单例模式在Tornado中的实现,以及适用场景和潜在局限。同时提到了with语句、super的使用以及threading.local()在多线程中的作用。
摘要由CSDN通过智能技术生成
[b]单例模式也是设计模式一书中介绍的23中设计模式之一。
[/b]Questions:
[list]
[*]1、@classmethod和@staticmethod 的用法与区别?
[*]2、Singleton的实现
[*]3、Singleton什么时候适合使用?
[/list]
问题1、
[quote]
A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.
A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance howdict.fromkeys(), a classmethod, returns an instance of the subclass when called on a subclass:[/quote]
示例:

#!/usr/bin/env python
#-*-encoding:utf-8-*-
class Demo:

def get(self,x):
print 'self and x is (%s,%s)'%(self,x)

@classmethod
def instance(cls,x):
print 'cls and x Is (%s,%s)'%(cls,x)

@staticmethod
def static(x):
print 'self and x is %s'%x

def main():
demo = Demo()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值