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

2024-04-25 05:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的课:

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项目。你知道吗


Tags: 方法inselfnodeifinitdefcoords
2条回答

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

class node:
    maxNum = 10000
    maxCoord = 10000.0

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

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

代码中有更多问题

  1. 定义setter时,需要一个property对象。你知道吗
  2. setter应该总是跟在getter后面,否则会出现namererror。你知道吗
class node:
    maxNum = 10000
    maxCoord = 10000.0

还可以使用node访问将行更改为if Coords[Key] > node.maxCoord: raise nodeCoordException。你知道吗

不相关,但类名应使用大写:class Node

相关问题 更多 >