I have a class with given elements. I know the element name (.name characteristic) as a line. How can I get having this line (let's say 'apple', the name of the .name object is also 'apple'), other specified characteristics of the apple object - mass, geometric dimensions?

  • one
    create an array with all the objects of the class / -s, then run through it, and for each of the elements to check whether the name - "apple"? - XxX
  • Unfortunately, all class objects are set "manually" inside the code as a list of 20,000 objects rolled into a spoiler. No quicker way? - Mark Yuhai

3 answers 3

# Класс у вас уже есть, привёл его просто для примера class products(object): def __init__(self, name, weight): self.weight = weight self.name = name # Ваши 20000 объектов, которые уже есть в коде: o1 = products('banana', 1) o2 = products('apple', 2) # .... o20000 = products('cherry', 3) # А вам нужно дописать что-то подобное # Перебираем все объекты в области видимости for obj in locals().values(): # Если объект является экземпляром класса products # и его свойство name равно 'apple' if isinstance(obj, products) and obj.name == 'apple': # Напечатаем значение его свойства weight print(obj.weight) # Напечатает только число 2, т.к. именно такой weight у объекта с name == 'apple' 
  • I duplicated your code for my class - I received an error: dictionary changed size during iteration - Mark Yuhai pm
  • I have a little answer rules, perhaps you ran an earlier version. Check that this line looks exactly like what I have now: for obj in locals (). Values ​​(): - Xander
  • for obj in locals (). values ​​(): RuntimeError: dictionary changed size during iteration Swears exactly on this line. - Mark Yuhai 2:24 pm
  • Strange, like it should not ... Try this: for obj in locals (). Copy (). Values ​​(): - Xander
  • import copy; copy.deepcopy(locals().values()) import copy; copy.deepcopy(locals().values()) ? - XxX
 class le_class(): def __init__(self, a, b): self.weight = a self.sort = b test = le_class(3,'red') print(test.weight) print(test.__dict__) # вернет словарь атрибутов экземпляра класса print(test.__class__.__name__) # вернет имя класса-родителя 

at the exit:

 3 {'weight': 3, 'sort': 'red'} le_class 
  • I did not quite understand how to use the class you specified. I apologize if the answer is obvious, master python 5 a day and can make stupid mistakes. - Mark Yuhai 1:56 pm
  • The problem is that the data is already initial in the code in the form: apple = products ('apple', weight = 20, linear = 3). I get the string 'apple' and I want to know the weight of the apple element using it. - Mark Yuhai

In addition to Alexander's answer, you can create variables by generating their name dynamically.

 # ... for i in [("Apple", 2), ("Banana", 10), ("Pineapple", 4)]: globals()["fruit%s" % i[0] = Fruit("%s" % i[0], i[1]) 

This will create N objects of the Fruit class, access to which can be obtained by knowing only their name.

 o = globals()["fruitApple"].weight # 2 

Thanks to this approach, it will be possible not to go through absolutely all objects, which will shorten the execution time.

  • Thank you very much, I will know, unfortunately the database for the class was not driven by me, but there is no desire to drive in so much data again. - Mark Yuhai
  • do you really have 20,000 lines occupied by class objects alone? - XxX
  • Yes, I received it as a default code, which needs to be improved and corrected as a task as part of university education. 1200 - 1500 lines of the code written by me and 20,000 on this class. - Mark Yuhai 2:32 pm