[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]
示例:
[/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()