【问题标题】:PyDev doesn't know what type array containsPyDev 不知道数组包含什么类型
【发布时间】:2014-07-08 21:43:28
【问题描述】:

您好,我在学了 1 年 java 后开始使用 Python,在学完 java 之后这是一个非常艰难的时刻,因为在 python 中,OO 方面的一切都是不同的,我在 Java 之前做了 2 年 PHP,所以 PHP 和 Python OO 方面都很不错类似。

到目前为止,我有这个脚本,这两个类:

import random

class Questions(object):

    questions = [Questions.Question("Is Jony mad?", False),
                 Questions.Question("Is Jony happy?", True)]

    currentQuestion = None;

    def __init__(self):
        pass


    def generateQuestion(self):
        self.currentQuestion = self.questions[random.randint(0, len(self.questions))]

    def answerQuestion(self, answer):
        if (answer == self.questions[0].

class Question:

    question = None
    answer = None

    def __init__(self, question, answer):
        self.question = question
        self.answer = answer

    def getQuestion(self):
        return self.question

    def getAnswer(self):
        return self.answer

它们位于一个名为 Questions 的文件中。

我有数组问题,应该包含Questions.QuestionQuestion 类)的对象。

一切都很好,直到我在方法answerQuestion 中到达这一行

def answerQuestion(self, answer):
    if (answer == self.questions[0].

当我做self.questions[0]. PyDev 没有给出该对象包含什么方法的建议,但是当我做self.currentQuestion. 我得到建议,但不是来自 Question 类,而是我得到数组的方法,例如 @987654329 @、remove(index)

我认为发生这种情况是因为 Eclipse PyDev 不知道 questions 数组是什么类型。

在 PHPStorm IDE 中,我通常使用 /** @var Object **/,但我是 Python 新手,我不太确定那里的工作原理。

我做错了什么吗?

【问题讨论】:

  • Python 语言过于动态,无法对列表中包含的内容做出假设。作为开发人员,您可能打算在该列表中仅包含 Question 对象,但 PyDev 无法做出这样的假设。

标签: python arrays pydev


【解决方案1】:

PyDev 无法假设 Python 列表包含什么;您可以在列表中存储任何内容,包括列表本身。

可以做出断言;如果你这样做了,那么 PyDev 对类型有足够的了解,因为否则断言会失败:

def answerQuestion(self, answer):
    question = self.questions[0]
    assert isinstance(question, Question)
    if answer == question.  # now auto-completion will work

看起来这只适用于直接引用的断言,而不适用于self.questions[0]

您也可以使用Sphinx or Epydoc style type assertion in a comment

def answerQuestion(self, answer):
    question = self.questions[0]  #: :type question Question
    if answer == question.  # now auto-completion will work

【讨论】:

  • 我刚试过,加点后好像什么都没变,什么也没出现
  • @BenBeri:是的,我自己实际上并没有使用 PyDev。您可能需要先执行question = self.questions[0],然后执行assert isinstance(question, Question),然后if answer == question. 将自动完成。
  • 其实不用assert,可以用cmets的type-hinting:pydev.org/manual_adv_type_hints.html
  • 不客气......不幸的是,PyDev 仍然不能处理类型容器——例如 list(int)——因为它不能处理类型推断中的结构,但最终它会做到这一点:)
  • @FabioZadrozny:对。我自己不是 PyDev 用户;我只是从其他工具的经验中推断出这种可能性存在,然后用谷歌搜索。 :-)
猜你喜欢
  • 2017-04-01
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多