python - 从类内部访问包含的静态信息的更好/正确方法

标签 python python-3.x

这是我的类(class):

class node:
    node.maxNum = 10000
    node.maxCoord = 10000.0

    def __init__(self, num = 0, **coordsIn):

        if num > node.maxNum: raise nodeNumException
        self.num = num

        ##set default args##
        coordsDefault = {'X' : float('NaN'), 'Y' : float('NaN')}

        ##set coordinates to input##
        self.coords = coordsIn

        @property.setter
        def coords(self, **Coords):
            for Key in Coords:
                if Coords[Key] > maxCoord: raise nodeCoordException
            ##Set _coords to default, then update from coordsIn##
            self._coords = coordsDefault.update(Coords)
        @property
        def coords(self):
            return self._coords

创建实例时,产生如下错误:

Traceback (most recent call last):
    File "(stdin)", line 1, in (module)
    File "C:\Projects\CANDE\mesh.py", line 7, in __init__
    if num > node.maxNum: raise nodeNumException
NameError: name 'maxNum' is not defined

我已经尝试通过几种不同的方式访问类中的 maxNummaxCoord 变量,但我似乎无法弄清楚如何避免此错误。

有没有办法修复我的代码并保持相同的方法?

另外:有没有更好的方法来做到这一点?任何建议,将不胜感激。这是我的第一个主要 Python 项目。

最佳答案

类变量在声明/定义时不需要类限定符。访问时只需要限定符

class node:
    maxNum = 10000
    maxCoord = 10000.0

    def __init__(self, num = 0, **coordsIn):

        if num > node.maxNum: raise nodeNumException
        self.num = num
        ........

你的代码有更多问题

  1. 定义setter时,需要一个属性对象。
  2. setter 应该始终跟在 getter 之后,否则你会得到一个 NameError。

关于python - 从类内部访问包含的静态信息的更好/正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26516251/

相关文章:

python - 通过循环使用元组键创建字典

python - 值错误 : Weights for model sequential have not yet been created

python - 如何概括文件函数以打开参数中提供的尽可能多的文本文件?

python - 数字 1-5 的所有组合总和 <=9

python - TypeError: 'float' 对象不可调用问题

python - SQLite DROP TABLE 语句的问题

python - 对 pandas 中相同的列名进行分组

python - 切片 python 字符串

python - 从命令行安装 python 并等待完成

python-3.x - ldap3 python 将用户添加到组