问题:**你想在 Python 中实现一个单例类,以确保只创建该类的一个实例。
解决方案: 要在 Python 中实现单例类,可以使用 __new__ 方法来控制类的实例化。
下面是一个 Python 单例类的简单示例:
class Singleton:
_instance = None # Private class variable to store the single instance
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
# Usage
singleton_1 = Singleton()
singleton_2 = Singleton()
print (singleton_1 is
Section 95.2: 表格编码数据
from requests import post
payload = {'key1' : 'value1',
'key2' : 'value2'
}
foo = post('http://httpbin.org/post', data=payload)
要通过 post 操作传递表单编码数据,必须将数据结构为字典,并作为数据参数提供。
如果数据不想被表单编码,只需在数据参数中传递一个字符串或整数即可。
向 json 参数提供字典,以便 Requests 自动格式化数据:
from requests import post
payload = {'key1' : 'value1', 'key2' : 'value2'}
foo = post('http://httpbin.org/post', json=payload)
Section 95.3: 上传文件
有了 Requests 模块,只需提供文件句柄,而不是用 .read()获取的内容:
from requests import post
files = {'file' : open('data.txt', 'rb')}
foo = post('http://http.org/post', files=files)
还可以设置文件名、内容类型和标题:
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel& singleton_2) # True (Both variables refer to the same instance)
在本例中,我们使用 __new__ 方法来控制实例的创建。_instance 变量用于存储单个实例。创建单例类的实例时,它会检查实例是否已经存在。如果存在,则返回现有实例;否则,创建一个新实例并将其存储在 _instance 变量中。
这种方法确保只创建一个 Singleton 类的实例,使它成为在 Python 中定义单子的一种简单而优雅的方法。