如何在类对象中引发“dtype”参数错误

我有以下代码:


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


如果有人知道的话,非常感谢。


拉莫斯之舞
浏览 146回答 1
1回答

函数式编程

Python 的结构完全由缩进级别控制:class circle(object):&nbsp; &nbsp; def __init__(self, radius=3, color='blue', data_type=np.float64):&nbsp; &nbsp;# default values&nbsp; &nbsp; &nbsp; &nbsp; self.radius = radius&nbsp; &nbsp; &nbsp; &nbsp; self.color = color&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; self.data_type = data_type&nbsp; &nbsp; &nbsp; &nbsp; # Python assumes this is the end of the __init__ function&nbsp; &nbsp; # because this next line is at the next higher level&nbsp; &nbsp; if self.data_type not in [np.float32, np.float64]:&nbsp; &nbsp; &nbsp; &nbsp; raise ValueError('data_type should be np.float32 or np.float64 only')&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; # so the above is a fragment that will not run in __init__.&nbsp;&nbsp; &nbsp; def add_radius(self, r):&nbsp; &nbsp; &nbsp; &nbsp; self.radius = self.radius + np.ceil(r, dtype=self.data_type)&nbsp; &nbsp; &nbsp; &nbsp; return(self.radius)这是否回答你的问题?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python