блиин (( я в печали
этот код работает
# -*- coding:utf-8 -*-
InstancesList = dict()
def get_instance_by_attribute(attr_name):
class wrapper(object):
def __init__(self, cls):
self.cls = cls
setattr(cls, "get_by_attr", self.get_by_attr)
def __call__(self, *args, **kwargs):
instance = self.cls(*args, **kwargs)
InstancesList.setdefault(self.cls, list()).append(instance)
return instance
def get_by_attr(self, value):
return [x for x in InstancesList[self.cls] if getattr(x, attr_name) == value]
return wrapper
@get_instance_by_attribute("key")
class Foo(object):
pass
class X(object):
file = []
def ololo(self):
f = Foo()
f.key = 1
f.d = 1
g = Foo()
g.key = 2
g.d = "ff"
h = Foo()
h.key = 3
h.d = False
j = Foo()
j.key = 4
j.d = 5.77
x = Foo()
x.key = 100500
x.d = 123
y = Foo()
y.key = 100500
y.d = "Bar"
self.file.append(f)
self.file.append(g)
self.file.append(h)
self.file.append(x)
self.file.append(y)
#def ololo2(self):
print self.file
for instance in Foo.get_by_attr(100500):
print instance, instance.d
Y = X()
Y.ololo()
#Y.ololo2()
а этот нет ( отрывок ) :
InstancesList = dict()
def get_instance_by_attribute(attr_name):
class wrapper(object):
def __init__(self, cls):
self.cls = cls
setattr(cls, "get_by_attr", self.get_by_attr)
def __call__(self, *args, **kwargs):
instance = self.cls(*args, **kwargs)
InstancesList.setdefault(self.cls, list()).append(instance)
return instance
def get_by_attr(self, value):
return [x for x in InstancesList[self.cls] if getattr(x, attr_name) == value]
return wrapper
@get_instance_by_attribute("file_name")
class excel_file_class(object): pass
class Ui_MainWindow(object):
list_of_files2 = []
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(720, 864)
..........................................................................
def open_excel(self):
# если в комбо-боксе установлено 'New', то продолжаем, если нет - ничего не делаем
if (self.cb_get(self.cb_filename) == 'New') :
# вызываем QT-Open, получаем путь до файла
temp_file = self.openFile()
# проверка на отмену Qt Open File
if temp_file == '' :
print '__ QT FileOpen __ действие отменено'
pass
else :
# если значение не пустое, то
# создаем обьект класса excel_file_class
file_list_temp = excel_file_class()
# заполняем путь до файла
file_list_temp.path_to_file = str( temp_file )
# получаем имя файла
file_list_temp.file_nane = self.int_split( file_list_temp.path_to_file )
# открываем excel файл.
# 0 - object of book
# 1 - num of sheet
# 2 - list of sheet name
temp = excel.open_xls(file_list_temp.path_to_file)
# первый (нулевой) элемент возвращенного списка - обьект книги ( см. выше )
file_list_temp.object_of_book = temp[0]
# второй (первый) элемент - количество страниц в книге
file_list_temp.num_of_sheets = temp[1]
# третий (второй) элемент - список имен страниц в книге
file_list_temp.name_of_sheets = temp[2]
# добавляем получившийся класс в переменную более высокого уровня
print self.list_of_files2
self.list_of_files2.append(file_list_temp)
# по идее проверку надо вкорячить где-то тут
# методом проб, проверка будет по имени.
if file_list_temp.file_nane in self.list_of_files :
# сделать всплывающее окно, в следующем релиз-кандидате гы-гы-гы
print 'дубликат? Не будет добавлен'
else :
# если значение уникально, то
self.list_of_files.append(file_list_temp.file_nane)
# добавляем итем в комбобокс
self.cb_add(file_list_temp.file_nane, self.cb_filename)
#при выборе файла в комбобоксе - обновить комбобокс страниц
#тестовый код
for instance in excel_file_class.get_by_attr('---.xls'):
print instance, instance.name_of_sheets
else :
print 'Выберете пункт New'
print 'end of open_excel'
код морально убог , я и сама начинаю путаться.
я просто хочу провести аналогию :
есть класс Ui_MainWindow(object)
в нем атрибут list_of_files2 = ( пустой список )
в функции ( или правильно - методе ? ) я .append'ю к нему класс ( всё как в первом примере ).
НО
for instance in excel_file_class.get_by_attr('---.xls'):
print instance, instance.name_of_sheets
грязно ругается :
Traceback (most recent call last):
File “/home/me/workspace/new_price/src/main_gui.py”, line 363, in open_excel
for instance in excel_file_class.get_by_attr('—.xls'):
File “/home/me/workspace/new_price/src/main_gui.py”, line 51, in get_by_attr
return [x for x in InstancesList if getattr(x, attr_name) == value]
AttributeError: ‘excel_file_class’ object has no attribute ‘file_name’
попой чувствую, что где-то напутала с пространством имен, но почему ? ведь первый приведенный код работает и еще как !!