0
我创建使用以下代码Singleton类(通过自我作为参数来新)差__new__
>>> class Singleton(object):
... IsSingleton = None
... def __new__(self):
... if self.IsSingleton == None:
... print "Singleton IF"
... self.IsSingleton = super(Singleton, self).__new__(self)
... print "ELSE"
... return self.IsSingleton
并且还使用CLS作为参数创建相同于新
>>> class Singleton(object):
... IsSingleton = None
... def __new__(cls):
... if cls.IsSingleton == None:
... print "Singleton IF"
... cls.IsSingleton = super(Singleton, cls).__new__(cls)
... print "ELSE"
... return cls.IsSingleton
我的问题是如果新是静态方法,如何将自我传递给静态方法不会出错?通过自我或cls到新的有什么区别。只要我已阅读,cls传递给新的不是自我。在两个不同的代码集中的上述相同的行为?
调用参数'cls'或'self'只是惯例。你可以称之为'x'或任何你想要的。但它是一个类,所以'cls'是它的合适名称。 – khelwood