python - 如何在类对象中为 `dtype`参数引发错误

标签 python numpy class error-handling

我有以下代码:

import numpy as np

class circle(object):
    def __init__(self, radius=3, color='blue', data_type=np.float64):   # default values
        self.radius = radius
        self.color = color 
        self.data_type = data_type
        
    if self.data_type not in [np.float32, np.float64]:
        raise ValueError('data_type should be np.float32 or np.float64 only')
        
    def add_radius(self, r):
        self.radius = self.radius + np.ceil(r, dtype=self.data_type)
        return(self.radius)
    
redcircle = circle(radius=10, color='red', data_type=np.float32)
redcircle.add_radius(2.323) 
运行代码时,出现以下错误:
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-39-27704fa7e57b> in <module>
----> 1 class circle(object):
      2     def __init__(self, radius=3, color='blue', data_type=np.float64):   # default values
      3         self.radius = radius
      4         self.color = color
      5         self.data_type = data_type

<ipython-input-39-27704fa7e57b> in circle()
      5         self.data_type = data_type
      6 
----> 7     if self.data_type not in [np.float32, np.float64]:
      8         raise ValueError('dtype should be np.float32 or np.float64 only')
      9 

NameError: name 'self' is not defined
我如何在一个类对象中指定dtype参数,以便如果指定的dtype参数值不是该类对象所接受的值,就会引发错误?
如果有人知道,请多谢。

最佳答案

Python的结构完全由缩进级别控制:

class circle(object):
    def __init__(self, radius=3, color='blue', data_type=np.float64):   # default values
        self.radius = radius
        self.color = color 
        self.data_type = data_type
        # Python assumes this is the end of the __init__ function

    # because this next line is at the next higher level
    if self.data_type not in [np.float32, np.float64]:
        raise ValueError('data_type should be np.float32 or np.float64 only')
    
    # so the above is a fragment that will not run in __init__. 

    def add_radius(self, r):
        self.radius = self.radius + np.ceil(r, dtype=self.data_type)
        return(self.radius)
这是否回答你的问题?

关于python - 如何在类对象中为 `dtype`参数引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63627001/

相关文章:

pandas - 如何将数据分成 3 组(训练、验证和测试)?

java - 引用自身的类如何工作?

php - 类型提示和默认参数值也是方法签名吗?

python - 如何使用 django.test.TestCase 断言异常?

python - 如何对字母数字 pandas 索引进行降序排序。

python - 如何在 Windows8 上安装 Pygame 以使用 Python 3.3.3?

python - 使用python将数字列表压缩为唯一的非重叠时间范围

python - 我需要 FFT wav 文件吗?

python - Python 中的类型和类

python - 如何使用字典键提取列表项?