generate.pycFile. When the second import is performed, the file is directly loaded..pycFile, instead of executing the module code again. Therefore, we only need to define the relevant functions and data in a module to obtain a singleton object.
Mysingleton. py
class Singleton: def foo(self): print('foo')singleton=Singleton()
Other files
from mysingleton import singletonsingleton.foo()
Decorator implementation
def singleton(cls): _insta
object.__new__(cls[, ... .. ])Called to create a new instance of class CLS. is __new__() a static method (special-cased so need not declare it as such) that takes the class of which an instance was Requested as its first argument. The remaining arguments is those passed to the object constructor expression (the call to the Class). The return value of __new__() should is the new object instance (usually an i
Method OneImplement the __new__ method, and then bind an instance of the class to the class variable _instance, or if cls._instance is None, the class has not been instantiated, new is an instance of the class, and returns, if Cls._instance is not none, Return directly to _instance, the code is as followsclassSingleton (object):def __new__(CLS, *args, * *Kwargs):
method for setting the related properties of an instanceWhen Python creates an instance, it calls the __new__ construction method and then initializes the instance using __init__.We can use __new__ to influence the creation of an instance, thus implementing a singleton.
Implementation code:
use_new.py
class Singleton(object): __instance = None def __new__(cls,*args,**kwargs): if not
, you Know ') def test_002 (self): Self.assertequal (Self.driver.current_url, ' https://www.baidu.com/') if __name__== ' __main__ ': unittest.main ( verbosity=2)After two, you will see open a browser two times, of course, close the browser is two times, this is not in progress. Can you let the test firmware execute onlyOnce, that is, in a test class, there are N test cases, after executing the test cases in this test class, the test firmware executes only once. Of course it is.Yes,
saved in the class variable, and if not, create one and then return ""If Singleton._instance is None:Singleton._instance = Singleton._a ()
def __getattr__ (self, attr):Return GetAttr (self._instance, attr)
if __name__ = = "__main__":# Create 2 instancesS1 = Singleton ()S2 = Singleton ()Print (ID (S1), S1.display ())Print (ID (S2), S2.display ())
Using adorners
The adorner maintains a Dictionary object instances, caches all singleton classes, creates if the singleton does not exist, and retu
The so-called Singleton refers to an instance of a class that can only be created once from beginning to end.Method 1Using the __new__ method is simple if you want a class to have at most one instance from start to finish. In Python, classes are created using __new__ to create an instance:Class Singleton (object): def __new__ (Cls,*args,**kwargs): If not hasattr (CLS, ' _inst '):
The __new__ () function can only be used for modern classes that inherit from object.First look at the definition of the __new__ () method in the object class:class object: @staticmethod # known case of __new__ def __new__(cls, *more): # known special case of object.__new__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """passObject defines the __new__ () method as a static method and requires at least one parameter
(CLS, * args, **kwargs): print ("Foo __new__", CLS, *args, **kwargs) return object.__new__ (CLS) f = Foo ("Shuaigaogao") # Output foo __new__ 3.2 New Method actionAction: All objects are instantiated with the new method, and new calls the Init method, so the new method is executed first in the instantiation process, not the Init method.① Reconstruc
)defTest (): Form=LoginForm ()if __name__=='__main__': App.run ()No. 0 Step:We'll see what happens when we define the LoginForm class.First we need to know another way of Metaclass:with_metaclassanother way to Metaclass:classMyType (type):def __init__(self,*args,**Kwargs):Print('xxxx') Super (mytype,self).__init__(*args,**Kwargs)def __call__(CLS, *args, * *Kwargs): obj= CLS.__new__(
DOCTYPE HTML>HTML>HeadLang= "en"> MetaCharSet= "UTF-8"> title>Addclass,removeclass,hasclass,toggleclass,getbyclasstitle>Head>Body>Divclass= "Div1"ID= "Box1">Div>inputtype= "button"value= "button"ID= "BTN1"/>Script> functionaddclass (obj,cls) {//obj: The element to add classname, CLS: the classname to add; //if the original class is not: if(Obj.classname== "') {Obj.classname=
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.