程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

8、 Python learning notes - object oriented - singleton mode

編輯:Python
# The singleton pattern : Always use the same instance ( object )
""" Application scenarios
1、 When creating resources to be reused in the course , Use the same instance , Avoid creating too many objects that waste time and resources
"""
# Example 1、 Demo singleton mode
class Foo:
__bar = None
@classmethod
def bar(cls):
if cls.__bar:
return cls.__bar
else:
cls.__bar = Foo() # In fact, the instantiation here
return cls.bar()
"""
1、 Do not use in singleton mode obj = class() Create objects this way ( In fact, the object is cls.__bar = Foo() Created here )
2、 The following code is just calling an object method , No matter how many calls are made, the same object ( example ) Methods , So the result is the same
"""
foo1 = Foo.bar()
print(foo1)
foo2 = Foo.bar()
print(foo2)
foo3 = Foo.bar()
print(foo3)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved