python中类初始化的最佳实践 - python

嗨,我想知道最佳实践是在python中初始化类,同时确保我的属性具有正确的数据类型。

我应该使用默认值初始化类属性还是调用检查功能?

class Foo:
    # Call with default value
    def __init__(self, bar=""):
         self._bar = bar

    # Calling set-function
    def __init__(self, bar):
        self._bar = ""
        self.set_bar(bar)

    def get_bar(self):
        return self._bar

    def set_bar(self, bar):
        if not isinstance(bar, str):
            raise TypeError("bar must be string")
        self._bar = bar

    def del_bar(self):
        self._bar = ""

    bar = property(get_bar, set_bar, del_bar, 'bar')

参考方案

您可以尝试以下代码片段:

class Foo:

    def __init__(self, bar=''):
        self.bar = bar

    @property
    def bar(self):
        return self._bar

    @bar.setter
    def bar(self, bar):
        if isinstance(bar, str):
            self._bar = bar
        else:
            raise TypeError('<bar> has to be of type string')

f = Foo('5') # works fine
g = Foo(5) # raises type error

即使在类的实例中未提供任何参数,也将进行检查。因此,即使您提供整数作为默认参数,它也会触发异常。

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…