1

假设我有以下两个课程。

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.

对以上有什么意见吗?有没有更好的方法来完成这项工作?

4

3 回答 3

1

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

目光短浅,虚伪。

可能拼错了一些东西,直到你忍受诉讼才发现,因为你没有进行单元测试。

“实际运行脚本”不是您学习是否正确执行的时间。

当您发现问题时,不使用 Eclipse 智能感知输入代码。

当您发现问题时,不会运行脚本。

单元测试是你发现问题的时候。

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

于 2010-11-05T23:38:41.807 回答
1

IntelliSense 只是不知道您想让它知道什么。想想这段代码:

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.
于 2010-11-06T00:51:34.213 回答
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 ...  
于 2010-11-05T23:42:08.130 回答