类的变量/方法 & 实例的变量/方法
# -*- coding: gb18030 -*-
class Singleton(object):
#变量在定义时候不区分“属于实例”还是“属于类”的
#在调用时候区分
# Singleton.__instance则是类的成员
# self.var则是实例的成员
__instance = None
var = 3
#类的方法
def __new__(cls, *args, **kwd):
if Singleton.__instance is None:
print "singleton"
#print "cls:", cls
#print "args:", args
#print "kwd:", kwd
Singleton.__instance = object.__new__(cls, *args, **kwd)
return Singleton.__instance
#实例方法
def doSth(self):
print "do sth", self.var
#类的方法
def doSth2(self):
print "do sth2", Singleton.var
class NonSingleton(object):
__instance = None
def __new__(cls, *args, **kwd):
print "non singleton"
NonSingleton.__instance = object.__new__(cls, *args, **kwd)
return NonSingleton.__instance
class MyClass(Singleton):
pass
class MyClass2(NonSingleton):
pass
a=MyClass()
b=MyClass()
a.doSth()
a.doSth2()
a.var=4
Singleton.var=5
a.doSth()
a.doSth2()
c=MyClass2()
d=MyClass2()