一个简单的例子 - 我想要一个点类来描述二维中的一个点。我希望能够将两个点相加......以及将两个点相乘(不要问我为什么),或者将一个点乘以一个标量。现在,我只会像标量是整数一样实现它,但分数或浮点数也很简单。
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x, self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
def __mul__(self, other):
if isinstance(other, Point):
x = self.x * other.x
y = self.y * other.y
return Point(x, y)
elif isinstance(other, int):
x = self.x * other
y = self.y * other
return Point(x, y)
Run Code Online (Sandbox Code Playgroud)
所以,这在我执行时有效:
>>> p1 = Point(2, 3)
>>> p2 = …
Run Code Online (Sandbox Code Playgroud) 我试图在我的图书馆中添加自定义格式字段。我知道这是通过Filter或LoggerAdapter对象完成的。但是,在我看到的示例中(像这样的示例:如何向Python日志格式字符串中添加自定义字段?),他们想要生成的自定义字段是静态的,并且在创建记录器时就知道了。
我需要能够将直到我写日志记录之前才真正知道的变量发送到我的日志记录。我想我只是没有看到解决方案,但是如何最好地做到这一点?
目前,我以这种方式设置记录器:
import logging
class MyClass:
filehandler = logging.handlers.RotatingRileHandler(r'C:\Users\Me\Desktop\Logs',
maxBytes=1000000, backupCount=4, encoding='ASCII')
formatter = logging.Formatter('[%(asctime)s] : %(levelname)-8s: Para: %(parameter)-15s'
' - %(message)s')
# parameter is my custom name I want to inject
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)
self.logger.addHandler(file_handler)
d = {'parameter': ''}
self.logger = logging.LoggerAdapter(self.logger, extra=d)
Run Code Online (Sandbox Code Playgroud)
在测试中,我写道:
my_obj = MyClass()
my_obj.logger.error('This is my error.', extra={'parameter': 'True'}
Run Code Online (Sandbox Code Playgroud)
但这会使参数字段''(空白字符串)始终为。有没有一种方法来设置d
字典中的每个我使日志调用(时间error()
,debug()
等等)?
我有一个工作项目。我们已经编写了一个模块,并在那里作为#TODO 来实现线程以改进模块。我是一个相当新的 Python 程序员,并决定尝试一下。在学习和实现线程时,我遇到了类似于多少线程太多的问题?因为我们有一个大约需要处理 6 个对象的队列,那么为什么在处理时间可以忽略不计的情况下创建 6 个线程(或任何线程)来处理列表或队列中的对象呢?(每个对象最多需要大约 2 秒来处理)
所以我做了一个小实验。我想知道使用线程是否有性能提升。请参阅下面的我的python代码:
import threading
import queue
import math
import time
results_total = []
results_calculation = []
results_threads = []
class MyThread(threading.Thread):
def __init__(self, thread_id, q):
threading.Thread.__init__(self)
self.threadID = thread_id
self.q = q
def run(self):
# print("Starting " + self.name)
process_data(self.q)
# print("Exiting " + self.name)
def process_data(q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
potentially_prime = True
data = q.get()
queueLock.release()
# check if the data is …
Run Code Online (Sandbox Code Playgroud)