2010-11-05 142 views
1

说我有以下两个类。Python Eclipse类型铸造智能感知解决方案

class TopClass: 
    def __init__(self): 
     self.items = [] 
class ItemClass: 
    def __init__(self): 
     self.name = None 

而且我想使用下列方式:

def do_something(): 
    myTop = TopClass() 
    # create two items 
    item1 = ItemClass() 
    item1.name = "Tony" 
    item2 = ItemClass() 
    item2.name = "Mike" 
    # add these to top class 
    myTop.items.append(item1) 
    myTop.items.append(item2) 
    # up until this point, access class members is effortless as the 
    # IDE (Eclipse) automatically recognizes the type of the object 
    # and can interpret the correct member variables. -- Awesome! 

    # now let's try and do a for loop 
    for myItem in myTop.items: 
     myItem.name # <- I HAD TO TYPE the ".name" IN MANUALLY, 
        # THIS IS ANNOYING, I could have misspelled 
        # something and not found out until 
        # I actually ran the script. 

    # Hacky way of making this easier 
    myItemT = ItemClass() 
    for myItemT in myTop.items: 
     myItemT.name = "bob" # <- Woah, it automatically filled in the 
          # ".name" part. This is nice, but I have the 
          # dummy line just above that is serving absolutely 
          # no purpose other than giving the 
          # Eclipse intellisense input. 

任何意见以上?有没有更好的方式来完成这项工作?

回答

1

我可能拼错了一些东西,直到我真正运行脚本时才发现。

短视和虚假。

可能拼写错误,直到你经历了一场官司,因为你没有进行单元测试。

“实际运行脚本”不是你学习的时候,如果你做得对。

有或无Eclipse智能感知的打字代码不是当您发现问题时。

运行脚本不是当你发现问题。

单元测试是在您发现问题时。

请停止依靠Eclipse智能感知。请开始单元测试。

+1

好吧,也许我想要这样的理由是错误的,如果我正在寻找的是让我的代码输入更有效。智能感知非常适合自动完成(特别是长会员名称)。所以我们说我只是想要这个,所以我不必输入太多。 – Nick 2010-11-05 23:56:26

+0

另外,单元测试确实是我应该确定某个东西是否正常工作的地方,但是至少不会在这里自动完成“帮助”原因。我不认为这是编码可靠性的破坏性特征。 – Nick 2010-11-06 00:01:27

+0

@Nick:这对动态语言完全有害。事实上,这有时会造成误导,并可能导致问题无法解决。但是,您可以在工作时自由使用它。当它不,你没有**丢失任何东西。你只需要像其他人一样打字。 – 2010-11-06 01:34:27

0

问题1:您可以将参数传递给__init__

class ItemClass: 
    def __init__(self, name): 
     self.name = name 

item1 = ItemClass("tony") # this is better 

问题2:请编辑为你工作,而不是组织你的代码编辑器。

myItemT = ItemClass() # this is misleading !! 

    # myItemT here is not same as above. What is some one changes this to x? 
    for myItemT in myTop.items: 
     ..... 

这可能会导致一个问题,因为不同的错误和编辑器不会帮助你在那里。

myItemT = ItemClass() 
for myItemT in myTop.items: 
    do_something_with myItemT ... 
# an indentation mistake 
# This myItemT refers to the one outside for block 
do_anotherthing_with myItemT ... 
1

智能感知就是不知道你想知道什么。想想这个代码:

class Foo(object): 
    def __init__(self): 
     self.name = None 

class Bar(object): 
    def __init__(self): 
     self.blub = None 

bar1 = Bar() 
bar2 = Bar() 
bar1.blub = 'joe' 
bar2.blub = 'jim' 

items = [bar1, bar2] 

each = Foo() 
for each in items: 
    each.name = 'Wha?' # here Eclipse also filled in the name attribute, 
         # although each is never a Foo in this loop. 
         # And funny, this is perfectly valid Python. 
         # All items now have a name attribute, despite being Bars.