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.
对于上面的内容,有什么看法吗?有没有更好的方法来实现这个?
3 个回答
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
我可能拼错了什么,直到我真正运行脚本时才发现。
这种想法太短视了,也不正确。
你可能拼错了什么,直到你因为没有进行单元测试而遭遇诉讼时才发现。
“真正运行脚本”并不是你发现自己做对了的时刻。
在输入代码时,不管有没有Eclipse的智能提示,都不是发现问题的时候。
运行脚本也不是发现问题的时候。
单元测试才是发现问题的时候。
请停止依赖Eclipse的智能提示。请开始进行单元测试。
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.