小编H.B*_*ari的帖子

根据值拆分Numpy数组

假设我有这个NumPy数组:

a = np.array([0, 3, 5, 5, 0, 10, 14, 15, 56, 0, 12, 23, 45, 23, 12, 45, 
              0, 1, 0, 2, 3, 4, 0, 0 ,0])
Run Code Online (Sandbox Code Playgroud)

我想在0之间打印所有数字并自动将它们添加到新的数字中np.array(见下文):

a1=[3, 5, 5]
a2=[10, 14, 15, 56]
a3=[12, 23, 45, 23, 12, 45]
a4=[1]
a5=[2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

是否有内置函数来执行此操作?

python numpy

9
推荐指数
2
解决办法
3541
查看次数

将默认列表参数传递给数据类

我想在我的班级中传递默认参数,但不知何故我遇到了问题:

from dataclasses import dataclass, field
from typing import List

@dataclass
class Pizza():
    ingredients: List = field(default_factory=['dow', 'tomatoes'])
    meat: str = field(default='chicken')

    def __repr__(self):
        return 'preparing_following_pizza {} {}'.format(self.ingredients, self.meat)
Run Code Online (Sandbox Code Playgroud)

如果我打字

>>> my_order = Pizza()
Traceback (most recent call last):
  File "pizza.py", line 13, in <module>
    Pizza()
  File "<string>", line 2, in __init__
TypeError: 'list' object is not callable
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

-------------------------------------------------- ------------------------- AttributeError Traceback(最近一次调用last)in()----> 1 Pizza.ingredients

AttributeError:类型对象'Pizza'没有属性'ingredients'

编辑:对于类实例我收到以下错误:

from dataclasses import dataclass, field
from typing import List

@dataclass
class Pizza():
    ingredients: …
Run Code Online (Sandbox Code Playgroud)

python oop type-hinting python-3.x

9
推荐指数
2
解决办法
4657
查看次数

未应用 Python @property setter 中的约束

我有一个非常简单的类,它将温度转换为华氏度,另外它确保值大于 -273

class Celsius:
    def __init__(self, temperature = 0):
        self._temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    @property
    def temperature(self):
        print('Getting_value')
        return self._temperature


    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value
Run Code Online (Sandbox Code Playgroud)

如果我运行以下代码

c = Celsius()
c.temperature=23
c.to_fahrenheit()
Run Code Online (Sandbox Code Playgroud)

我得到预期的输出:

Setting value
Getting_value
Out[89]:
73.4
Run Code Online (Sandbox Code Playgroud)

现在试图将温度设置为 -275,我们得到了预期的错误!

c = Celsius()
c.temperature=-275
c.to_fahrenheit()
Run Code Online (Sandbox Code Playgroud)

-------------------------------------------------- ------------------------- ValueError Traceback (最近一次调用最后一次) in () 1 c =Celsius() ----> 2 c.温度=-275 3 c.to_fahrenheit() …

python python-3.x

2
推荐指数
1
解决办法
658
查看次数

标签 统计

python ×3

python-3.x ×2

numpy ×1

oop ×1

type-hinting ×1