Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sorting
#4
A container must implement the methods __lt__, __gt__, __eq__ to be sortable.
With your code and some additions it looks like this:

from functools import total_ordering


@total_ordering
class Catalog(object):
    # names of classes should begin with upper case
    sort_order = ['pret', 'consum', 'producator', 'cod_produs']
    lista_obiecte = [] #list_of_objects
    clasa = ""
    subclasa = ""
 
    def __init__(self):
        self.pret = int(input("Pretul produsului: ")) #price
        self.consum = int(input("Consumul produsului: ")) #cconsumption  
        self.producator = input("Producatorul produsului: ") #manufacture
        self.cod_produs = int(input("Codul produsului: ")) #series_number
        catalog.lista_obiecte.append(self)
    
    def _get_fields(self):
        return tuple(getattr(self, field) for field in self.sort_order)
        
    def __lt__(self, other):
        return self._get_fields() < other._get_fields()
    def __gt__(self, other):
        return self._get_fields() > other._get_fields()
    def __eq__(self, other):
        return self._get_fields() == other._get_fields()
    def __repr__(self):
        return f'{self.__class__.__name__}(pret={self.pret})'

# the _get_fields method is just a helper.
# I would not repeat myself.
With Python 3.7 dataclasses were introduced.
They give you the dot-access, the can be sortable and frozen (imutable)
Representation is made automatic. With fields you can also define if a filed should not
be used for sorting. It looks also a little bit cleaner.
You need to know, that you should not overwrite the __init__ method, if you are using dataclasses.

from dataclasses import dataclass
from dataclasses import field


def get_input_with_validation(question, input_type=int, min_val=None, max_val=None):
    while True:
        data = input(question + ': ')
        try:
            value = input_type(data)
        except ValueError:
            print(f'{data} is not a {input_type.__name__}')
            continue
        if min_val is not None and value < min_val:
            print(f'{value} is smaller than {min_val}')
            continue
        if max_val is not None and value > max_val:
            print(f'{value} is bigger than {max_val}')
            continue
        return value 


@dataclass(order=True, frozen=True)
class Item:
    pret: int = field()
    consum : int = field()
    producator: int = field(repr=False)
    cod_produs: int = field(repr=False)
    
    @classmethod
    def create(cls):
        pret = get_input_with_validation("Pretul produsului")
        consum = get_input_with_validation("Consumul produsului")
        producator = get_input_with_validation("Producatorul produsului")
        cod_produs = get_input_with_validation("Codul produsului")
        return cls(pret, consum, producator, cod_produs)
The sorted function does the rest.
The order of fields counts also.
With this example the Item is sorted by (price, consum)
and the rest was excluded from sorting.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
sorting - by AG17 - Jul-25-2019, 08:54 PM
RE: sorting - by ichabod801 - Jul-25-2019, 09:01 PM
RE: sorting - by AG17 - Jul-26-2019, 04:18 AM
RE: sorting - by DeaD_EyE - Jul-26-2019, 09:08 AM
RE: sorting - by ichabod801 - Jul-26-2019, 12:17 PM
RE: sorting - by AG17 - Jul-26-2019, 07:12 PM
RE: sorting - by ichabod801 - Jul-26-2019, 07:24 PM
RE: sorting - by liviu_dirlescu - May-04-2020, 02:09 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020