【问题标题】:Python instance and class namespacesPython 实例和类命名空间
【发布时间】:2017-05-02 15:25:58
【问题描述】:

我是 Python 新手,熟悉 Java 和 C#,所以下面的代码可能完全不是 Python 的。 我正在尝试获取我的类向量实例的索引值,其中包含的整数列表名为 vec。

class Vector:
def __init__(self,*args,**kwargs):
    if(args and args.length()>=2):
        self.dimension=args[0]
        self.vec=args[1]
    elif(kwargs):
        if(kwargs.get('vec')):
            self.vec=kwargs.get('vec')
            self.dimension=len(self.vec)
        elif(kwargs.get('n')):
            self.dimension=kwargs.get('n')
            nulllist=[]
            for x in range(0,kwargs.get('n')):
                nulllist.append(0)
            self.vec=nulllist

def __getitem__(v,i):
    if(v.vec[i]):
        return v.vec[i]
    else:
        return "None"

当我试图得到 v0 = Vector(n=2) assert(v0[0] == 0)

我得到一个断言错误,因为 v0[0] 返回“无” 如果我 print(v0[0]) 打印输出为“无”

我做错了什么? 提前非常感谢。

【问题讨论】:

  • if(v.vec[i]) - 你认为这有什么作用?

标签: python class namespaces instance scopes


【解决方案1】:

零的布尔解释是错误的。因此,如果 v.vec[i] 为零,您的 if(v.vec[i]): 将为 false,并且不会输入 if 块。

目前尚不清楚您要使用 if 测试什么。如果您尝试测试元素是否存在,则不会这样做。您可能会更好地执行以下操作:

try:
    return v.vec[i]
except IndexError:
    return None

(也不确定您为什么要返回 "None" 而不是 None,但如果您愿意,当然可以修改我的示例来做到这一点。)

【讨论】:

    【解决方案2】:

    您应该在构造函数中初始化 self.vec(如果没有调用 if 和 elif)。

    class Vector:
        def __init__(self,*args,**kwargs):
            self.vec = None
            ...
    
    
    v0 = Vector(n=2)
    if v0.vec is not None:
        print('Vector defined')
    else:
        print('ERROR: No Vector !')
    

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 2022-12-31
      • 1970-01-01
      相关资源
      最近更新 更多