小编Edu*_*rdo的帖子

只计算一次属性并多次使用结果(不同的方法)

我试图多次使用类方法的结果,而不进行获得结果所需的繁重计算。

我看到以下选项。你认为哪些是正确的,或者更像 Pythonic?

每一种的优点和缺点是什么?

尝试/除外方法

class Test:
    def __init__(self, *args):
        # do stuff

    @property
    def new_method(self):
        try:
            return self._new_property
        except AttributeError:
            # do some heavy calculations
            return self._new_property
Run Code Online (Sandbox Code Playgroud)

lru_cache 方法

from functools import lru_cache

class Test:
    def __init__(self, *args):
        # do stuff

    @property
    @lru_cache()
    def new_method(self):
        # do some heavy calculations
        return self._new_property
Run Code Online (Sandbox Code Playgroud)

Django 的 cache_property 方法

from django.utils.functional import cached_property

class Test:
    def __init__(self, *args):
        # do stuff

    @cached_property
    def new_method(self):
        # do some heavy calculations
        return self._new_property
Run Code Online (Sandbox Code Playgroud)

python properties class-method

7
推荐指数
1
解决办法
1229
查看次数

脾气暴躁的多重条件

我需要使用numpy处理多个条件。

我正在尝试这段似乎可行的代码。

我的问题是:还有另一种方法可以完成相同的工作?

Mur=np.array([200,246,372])*pq.kN*pq.m
Mumax=np.array([1400,600,700])*pq.kN*pq.m
Mu=np.array([100,500,2000])*pq.kN*pq.m
Acreq=np.where(Mu<Mur,0,"zero")
Acreq=np.where(((Mur<Mu)&(Mu<Mumax)),45,Acreq)
Acreq=np.where(Mu>Mumax,60,Acreq)
Print(Acreq)
['0' '45' '60']
Run Code Online (Sandbox Code Playgroud)

python numpy where

3
推荐指数
1
解决办法
6093
查看次数

标签 统计

python ×2

class-method ×1

numpy ×1

properties ×1

where ×1