Обход IntelliSense для приведения типов в Python Eclipse - PullRequest
1 голос
/ 06 ноября 2010

Скажите, у меня есть следующие два класса.

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 ]

1 голос
/ 06 ноября 2010

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.
1 голос
/ 06 ноября 2010

Я мог что-то написать с ошибкой и не узнал, пока не запустил скрипт.

Близорук и ложь.

Вы могли что-то неправильно написали и никогда не узнавали, пока вы не выдержали судебный процесс, потому что вы не провели юнит-тестирование.

«фактически запустил скрипт» - это не время, когда вы узнаете, правильно ли вы это сделали.

Ввод кода с или без Eclipse intellisense не когда вы обнаружите проблемы.

Запуск сценария выполняется не тогда, когда вы обнаруживаете проблемы.

Модульное тестирование - это когда вы обнаруживаете проблемы.

Пожалуйста, перестаньте полагаться на Eclipse intellisense.Пожалуйста, начните модульное тестирование.

0 голосов
/ 06 ноября 2010

Проблема 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 ...  
...