从Python 3.4开始,Enum该类存在.
我正在编写一个程序,其中一些常量有一个特定的顺序,我想知道哪种方式是比较它们最pythonic:
class Information(Enum):
ValueOnly = 0
FirstDerivative = 1
SecondDerivative = 2
Run Code Online (Sandbox Code Playgroud)
现在有一种方法,需要将给定information的Information与不同的枚举进行比较:
information = Information.FirstDerivative
print(value)
if information >= Information.FirstDerivative:
print(jacobian)
if information >= Information.SecondDerivative:
print(hessian)
Run Code Online (Sandbox Code Playgroud)
直接比较不适用于Enums,所以有三种方法,我想知道哪一种是首选的:
方法1:使用值:
if information.value >= Information.FirstDerivative.value:
...
Run Code Online (Sandbox Code Playgroud)
方法2:使用IntEnum:
class Information(IntEnum):
...
Run Code Online (Sandbox Code Playgroud)
方法3:根本不使用枚举:
class Information:
ValueOnly = 0
FirstDerivative = 1
SecondDerivative = 2
Run Code Online (Sandbox Code Playgroud)
每种方法都有效,方法1有点冗长,而方法2使用不推荐的IntEnum类,而方法3似乎就是在添加Enum之前这样做的方式.
我倾向于使用方法1,但我不确定.
谢谢你的任何建议!
我想用一个程序启动几个子进程,即一个模块foo.py启动几个实例bar.py.
由于我有时必须手动终止进程,因此我需要进程id来执行kill命令.
即使整个设置非常"脏" pid,如果过程是通过启动进行的,还是有一种很好的pythonic方式来获取进程os.system吗?
foo.py:
import os
import time
os.system("python bar.py \"{0}\ &".format(str(argument)))
time.sleep(3)
pid = ???
os.system("kill -9 {0}".format(pid))
Run Code Online (Sandbox Code Playgroud)
bar.py:
import time
print("bla")
time.sleep(10) % within this time, the process should be killed
print("blubb")
Run Code Online (Sandbox Code Playgroud) 如果我有一个非空HashSet<T> items,这两行有没有快捷方式:
T item = items.First(); // this can be any item, it does not have to be the first one
items.Remove(item);
Run Code Online (Sandbox Code Playgroud)
我认为T item = items.Pop()这是一个合适的函数,但它不存在。
我知道,拥有两行或编写扩展方法没什么大不了的,但我不知何故期望有一个内置Pop()函数,它不依赖于First().
编辑:
由于存在一些困惑First():我绝对不关心从 中弹出哪个项目HashSet,所以items.Last()对我来说也可以。
这种关于使用的混乱First()是我苦苦挣扎的一点:即使我评论了它,阅读代码也会导致这样的假设:使用它在某种程度上很重要First()(事实并非如此)。
所以澄清一下:我想知道,是否有一种正确的方法,从 a 中取出某些项目HashSet,将其用于进一步使用,并且不要给人留下这样的印象,它必须是第一个或最后一个或任何项目,而是要清楚,此时可以选择任何项目。
我使用池来获益多核.池中的每个worker都需要自己的Calculator对象.计算器的初始化非常耗时,所以我想让它在池中每个工作者只生成一次,而不是每次都有新的任务到来.唯一的方法,我得到的工作是使用"丑陋"关键字global.是否有一种"更清洁"的方式来实现这一点?
我想避免队列(父线程通常是sigkill'd并在使用队列时留下子进程)和管理器(性能太慢).
#!/usr/bin/python
# -*- coding: utf-8 -*-
import multiprocessing
def init_pool():
global calculator
calculator = Calculator() # should only executed ones per worker
def run_pool(args):
return calculator.calculate(*args) # time consuming calculation
class Organiser():
def __init__(self):
self.__pool = multiprocessing.Pool(initializer=init_pool)
def process(self, tasks):
results = self.__pool.map(run_pool, tasks)
return results
Run Code Online (Sandbox Code Playgroud) 我正在研究类似这里的东西(带有 sqlalchemy 的多线程应用程序),所以我明白,我应该为每个 db-query 创建一个新会话。
我想知道,如果为每个需要 DB 访问的方法使用装饰器是否有意义,或者是否存在使用这种方法的陷阱。装饰器是按照此处的最后一个示例构建的。
def dbconnect(func):
def inner(*args, **kwargs):
session = Session() # with all the requirements
try:
func(*args, session=session, **kwargs)
session.commit()
except:
session.rollback()
raise
finally:
session.close()
return inner
@dbconnect
def some_function(some, arguments, session)
session.query(...) # no commit, close, rollback required
some_function("many", "different_arguments")
#session is not required, since provided by decorator
Run Code Online (Sandbox Code Playgroud)
这将使为任何函数提供线程安全的 DB 访问变得相当容易,而无需实现整个 try-except-finally-stuff 冗余,但我不确定,如果这种方法是故障安全的和 pythonic,或者是否存在其他最佳实践。
我想知道,max在关于特定属性的对象列表中使用最可能的pythonic方式.假设有这个类:
class Foo():
def __init__(self, value):
self.value = value
Run Code Online (Sandbox Code Playgroud)
现在有一个Foos 列表:
foos = [Foo(2), Foo(3), Foo(1)]
Run Code Online (Sandbox Code Playgroud)
我希望有最大价值这一名单.
我可以max在列表上使用:
max_value = max([foo.value for foo in foos])
Run Code Online (Sandbox Code Playgroud)
这总是首先构造一个列表(可能会降低巨大列表的性能),所以我想使用这个key参数:
max_value = max(foos, key=lambda foo: foo.value).value
Run Code Online (Sandbox Code Playgroud)
这看起来有点难看,因为我没有得到属性,而是对象.
我还可以定义__eq__,__le__里面的功能Foo,但是这将限制使用max特定值,我不能使用max一个以上的属性.
还有另一种方法,以一种漂亮的pythonic方式获得最大值吗?
我有一个 Visual Studio 2017 解决方案,它分为多个 C#-WinForm 应用程序。
为了拥有类似的用户界面,我将所有图标/图片放入一个项目(ResourceProject)中,并将资源文件标记为公共。
通过直接编辑表单的 .Designer 文件,我现在可以通过声明将图像显式分配给 ResourceProject 的资源文件中的某些内容
button1.Image = ResourceProject.Properties.Resources.DemoPic
Run Code Online (Sandbox Code Playgroud)
然而,设计者有时会用以下内容覆盖它:
button1.Image = ((System.Drawing.Image)resources.GetObject("button1.Image")));
Run Code Online (Sandbox Code Playgroud)
并创建一个嵌入图像的本地资源文件。
这正是我首先想要避免的,因为我可能想稍后轻松地更改一些图标并将这些更改直接传播到所有项目。
避免这种情况的唯一方法似乎是不在设计器文件中分配图像,而是在实际表单文件中以其他方法分配图像。
还有其他方法可以解决这个问题吗?