Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
method call help
#1
bonjour,
Je reçois une résultat non qui j'attend, et je ne sais pas pourquoi ?
quand j'appel la méthode pricing_mac(self): de class HardwareGeek(EmployeeHardware): le prix ne change pas, :

quand :
kim.pricing_intel() # on passe au tarif "PC"
project_o.perform(kim, "achat matériel PC", 0.5)
kim.pricing_mac() # on passe au tarif "MAC"
project_o.perform(kim, "achat matériel MAC", 1.5)
project_o.perform(ali, "configuration matériel", 2)
project_o.perform(ali, "installation chez client", 3)

il affiche :

Kim achat matériel PC 65.00€/h 0.50h 32€
Kim achat matériel MAC 75.00€/h 1.50h 112€
Ali configuration matériel 0.00€/h 2.00h 0€
Ali installation chez client 0.00€/h 3.00h 0€

moi je veux cette affiche:
Kim achat matériel PC 65.00€/h 0.50h 32€
Kim achat matériel MAC 75.00€/h 1.50h 112€
Ali configuration matériel 50.00€/h 2.00h 100€
Ali installation chez client 50.00€/h 3.00h 150€

Ceci est mon code :
from abc import ABC, abstractmethod
 
 
class InvoiceCalc:
    """
    Calcul des montants à facturer
    """
    __taux_tva = 0.21
    __instance = None
 
    @classmethod
    def singleton(taux_tva):
        if not InvoiceCalc.__instance:
            InvoiceCalc.__instance = InvoiceCalc()
            InvoiceCalc.__instance.__taux_tva = InvoiceCalc(taux_tva)
 
    def __init__(self):
     pass
 
    def compute_perform(self, price, dur):
        """ calcule le montant à facturer (htva, tva, ttc)
            pour cet employé "emp" et
            pour cette durée de prestation  "dur"
            avec le tarif horaire "price" = emp.price
        """
        montant = dur * price
        return self.compute_expense(montant)
 
    def compute_expense(self, exp):
        """ calcule et retourne le montant à facturer (htva, tva, ttc)
            pour cette dépense "exp"
        """
        montant = exp
        tva = montant * self.__taux_tva
        montant_ttc = montant + tva
        return ( montant, tva, montant_ttc )
 
class Project:
    """
    Gestion des enregistrements du temps d'un employé
    sur un projet pour un client.
    A ne pas modifier !
    """
    def __init__(self, project="", client=""):
        self.__client = ""
        self.__project = project
        self.__perform_l = []
        self.__expense_l = []
        self.__client = client
 
    def perform(self, emp, det, dur):
        if isinstance(emp, Employee):
            self.__perform_l.append({
                "name":     emp.name,
                "detail":   det,
                "duration": float(dur),
                "price":    emp.price
            })
 
    def expense(self, emp, subject, amount):
        self.__expense_l.append({
            "name":   emp.name,
            "detail": subject,
            "amount": float(amount)
        })
 
    def __iter__(self):
        self.index = 0
        self.inv_calc = InvoiceCalc()
        return self
 
    def __next__(self):
        if self.index >= len(self.__expense_l):
            raise StopIteration
        data = self.__expense_l[self.index]
        self.index += 1
        amount = data['amount']
        htva, tva, ttc = self.inv_calc.compute_expense(amount)
        return f'{data["detail"]},{htva},{tva},{ttc}'
        #return data
 
    def __str__(self):
        # templates
        header_s = \
    """
    Client  : {1}
    Projet  : {2}
 
    """
        header_perform_s = \
    """
    Détail des prestations (h, €)
    """
        header_expense_s = \
    """
    Détail des dépenses (€)
    """
        perform_str = "{2:8} {0:26} {5:>6.2f}€/h {1:>6.2f}h {4:>6.0f}€\n"
        expense_str = "{2:8} {0:26}                   {4:>6.0f}€\n"
        title_str = "{2:^8} {0:^26} {5:^8} {1:^9} {4:^7}\n"
        t_p = 0  # total prestation
        t_i = 0  # total facturation
        t_e = 0  # total expense
        final_fs = ""
 
        # header
        final_fs += header_s.format("", self.__client, self.__project)
 
        # body "perform"
        final_fs += header_perform_s
        final_fs += title_str.format("TASK", "DUR", "PERSON", "DEPT", "INV", "PRICE")
        for data in self.__perform_l:
            inv_c = InvoiceCalc()
            to_invoice_tuple = inv_c.compute_perform(data["price"], data["duration"])
            final_fs += perform_str.format(
                data["detail"],
                data["duration"],
                data["name"],
                "",
                to_invoice_tuple[0],
                data["price"]
            )
            t_p += data["duration"]
            t_i += to_invoice_tuple[0]
        final_fs += "\n" + perform_str.format("Total perform", t_p, "", "", t_i, 0) + "\n"
 
        # body "expense"
        final_fs += header_expense_s
        final_fs += title_str.format("EXPENSE", "", "PERSON", "DEPT", "INV", "")
        for data in self.__expense_l:
            inv_c = InvoiceCalc()
            to_invoice_tuple = inv_c.compute_expense(data["amount"])
            final_fs += expense_str.format(
                data["detail"],
                0,
                data["name"],
                "",
                to_invoice_tuple[0]
            )
            t_e += to_invoice_tuple[0]
        final_fs += "\n" + expense_str.format("Total expense", 0, "", "", t_e) + "\n"
 
        # footer
        final_fs += "\n" + expense_str.format("Total général", 0, "******", "***********", t_e + t_i) + "\n"
 
        return final_fs
 
 
class Employee(ABC):
    def __init__(self, name):
        self.name = name
 
    @property
    @abstractmethod
    def price(self):
        return self.price
        #pass
 
    @property
    @abstractmethod
    def department(self):
        return self.department
        #pass
 
    @classmethod
    def factory(self, name, function):
        if function == "Geek":
            return Geek(name)
        elif function == "hardware":
            return HardwareGeek(name)
        elif function == "technical manager":
            return TechnicalManager(name)
        elif function == "account manager":
            return AccountManager(name)
        else:
            raise ValueError("Unknown employee type")
        #return EmployeeFake(name)
 
 
class EmployeeFake(Employee):
    department = "circus"
    price = 15
 
 
class EmployeeHardware(Employee):
    department = "hardware"
    project_o = Project("installation de deux PC", "Lehman Brothers Bank")
    emp = "kim"
    det = {"achat matériel MAC", "configuration matériel", "installation chez client"}#"detail"
    dur = 0
    project_o.perform(emp, det, dur)
    detail = det
 
class Geek(EmployeeHardware):
    price = 60
 
 
class HardwareGeek(EmployeeHardware):
    price = 0
 
    # fonction à déplacer dans la bonne classe
 
    def pricing_intel(self):
        self.price = 65
        return self.price
        # pass
 
    def pricing_mac(self):
 
        detail = {"achat matériel MAC", "configuration matériel", "installation chez client"}
        if detail == "achat matériel MAC":
            self.price = 75
        if detail == "configuration matériel":
            self.price = 50
        elif detail == "installation chez client":
            self.price = 50
        else :self.price = 75
  
class TechnicalManager(EmployeeHardware):
    price = 90
 
 
class AccountManager(Employee):
    department = "account"
    price = 100
 
 
 
if __name__ == '__main__':
    #
 
    # 1)
    kim = Employee.factory("Kim", "hardware" )  # return HardwareGeek object
    ali = Employee.factory("Ali", "hardware" )  # return HardwareGeek object
    albert = Employee.factory("Albert", "technical manager") # return TechnicalManager object
    sophie = Employee.factory("Sophie", "account manager")   # return AccountManager object
 
    # 2)
    project_o = Project("installation de deux PC", "Lehman Brothers Bank")
 
    # 3)
    project_o.perform(albert, "réunion avec client", 1)
    kim.pricing_intel() # on passe au tarif "PC"
    project_o.perform(kim, "achat matériel PC", 0.5)
    kim.pricing_mac()   # on passe au tarif "MAC"
    project_o.perform(kim, "achat matériel MAC", 1.5)
    project_o.perform(ali, "configuration matériel", 2)
    project_o.perform(ali, "installation chez client", 3)
    project_o.perform(albert, "remise des clés", 0.5)
    project_o.perform(sophie, "convention avec le client", 0.5)
 
    # on ajoute des dépenses
    project_o.expense(kim, "deux PC et accessoires", 1500)
    project_o.expense(kim, "trois MAC et accessoires", 4500)
 
    print(project_o)
 
    # 4)
    print("CSV")
 
    project_it = iter(project_o)
    while True:
        try:
            # iteration
            csv = next(project_it)
            print(csv)
        except StopIteration:
            # quand tous les enregistrements ont été reçus
            break
*merci pour l'aide*
Yoriz write Feb-19-2023, 03:32 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
Google translation

Good morning,
I get a result not which I expect, and I don't know why?
when I call the pricing_mac(self): method of class HardwareGeek(EmployeeHardware): the price does not change, :

When :
kim.pricing_intel() # switch to "PC" pricing
project_o.perform(kim, "PC hardware purchase", 0.5)
kim.pricing_mac() # switch to "MAC" pricing
project_o.perform(kim, "MAC hardware purchase", 1.5)
project_o.perform(ali, "hardware configuration", 2)
project_o.perform(ali, "customer installation", 3)

it displays :

Kim PC hardware purchase 65.00€/h 0.50h 32€
Kim purchase of MAC equipment 75.00€/h 1.50h 112€
Ali hardware configuration 0.00€/h 2.00h 0€
Ali installation at customer 0.00€/h 3.00h 0€

I want this poster:
Kim PC hardware purchase 65.00€/h 0.50h 32€
Kim purchase of MAC equipment 75.00€/h 1.50h 112€
Ali hardware configuration 50.00€/h 2.00h 100€
Ali installation at customer 50.00€/h 3.00h 150€

This is my code:
from abc import ABC, abstractmethod
  
  
class InvoiceCalc:
     """
     Calculation of amounts to be invoiced
     """
     __vat_rate = 0.21
     __instance = None
  
     @classmethod
     def singleton(vat_rate):
         if not InvoiceCalc.__instance:
             InvoiceCalc.__instance = InvoiceCalc()
             InvoiceCalc.__instance.__vat_rate = InvoiceCalc(vat_rate)
  
     def __init__(self):
      pass
  
     def compute_perform(self, price, hard):
         """ calculates the amount to be invoiced (htva, vat, ttc)
             for this employee "emp" and
             for this duration of "hard" performance
             with the hourly rate "price" = emp.price
         """
         amount = hard * price
         return self.compute_expense(amount)
  
     def compute_expense(self, exp):
         """ calculates and returns the amount to be invoiced (htva, vat, ttc)
             for this expense "exp"
         """
         amount = exp
         vat = amount * self.__tax_tva
         amount_ttc = amount + vat
         return ( amount, vat, amount_ttc )
  
class Project:
     """
     Managing an employee's time records
     on a project for a client.
     Do not modify!
     """
     def __init__(self, project="", client=""):
         self.__customer = ""
         self.__project = project
         self.__perform_l = []
         self.__expense_l = []
         self.__customer = customer
  
     def perform(self, emp, det, hard):
         if isinstance(emp, Employee):
             self.__perform_l.append({
                 "name": emp.name,
                 "detail": det,
                 "duration": float(duration),
                 "price": emp.price
             })
  
     def expense(self, emp, subject, amount):
         self.__expense_l.append({
             "name": emp.name,
             "detail": subject,
             "amount": float(amount)
         })
  
     def __iter__(self):
         self.index = 0
         self.inv_calc = InvoiceCalc()
         return self
  
     def __next__(self):
         if self.index >= len(self.__expense_l):
             raise StopIteration
         data = self.__expense_l[self.index]
         self.index += 1
         amount = data['amount']
         excl. vat, vat, ttc = self.inv_calc.compute_expense(amount)
         return f'{data["detail"]},{htva},{tva},{ttc}'
         #return data
  
     def __str__(self):
         # templates
         header_s=\
     """
     Customer: {1}
     Project: {2}
  
     """
         header_perform_s=\
     """
     Detail of services (h, €)
     """
         header_expense_s=\
     """
     Details of expenses (€)
     """
         perform_str = "{2:8} {0:26} {5:>6.2f}€/h {1:>6.2f}h {4:>6.0f}€\n"
         expense_str = "{2:8} {0:26} {4:>6.0f}€\n"
         title_str = "{2:^8} {0:^26} {5:^8} {1:^9} {4:^7}\n"
         t_p = 0 # total service
         t_i = 0 # total billing
         t_e = 0 # total expense
         final_fs = ""
  
         # header
         final_fs += header_s.format("", self.__client, self.__project)
  
         # body "perform"
         final_fs += header_perform_s
         final_fs += title_str.format("TASK", "HARD", "PERSON", "DEPT", "INV", "PRICE")
         for data in self.__perform_l:
             inv_c = InvoiceCalc()
             to_invoice_tuple = inv_c.compute_perform(data["price"], data["duration"])
             final_fs += perform_str.format(
                 data["detail"],
                 data["duration"],
                 data["name"],
                 "",
                 to_invoice_tuple[0],
                 data["price"]
             )
             t_p += data["duration"]
             t_i += to_invoice_tuple[0]
         final_fs += "\n" + perform_str.format("Total perform", t_p, "", "", t_i, 0) + "\n"
  
         # body "expense"
         final_fs += header_expense_s
         final_fs += title_str.format("EXPENSE", "", "PERSON", "DEPT", "INV", "")
         for data in self.__expense_l:
             inv_c = InvoiceCalc()
             to_invoice_tuple = inv_c.compute_expense(data["amount"])
             final_fs += expense_str.format(
                 data["detail"],
                 0,
                 data["name"],
                 "",
                 to_invoice_tuple[0]
             )
             t_e += to_invoice_tuple[0]
         final_fs += "\n" + expense_str.format("Total expense", 0, "", "", t_e) + "\n"
  
         # footer
         final_fs += "\n" + expense_str.format("Grand total", 0, "******", "***********", t_e + t_i) + "\n "
  
         return final_fs

class Employee(ABC):
     def __init__(self, name):
         self.name = name
   
     @property
     @abstractmethod
     def price(self):
         return self.price
         #pass
   
     @property
     @abstractmethod
     def department(self):
         return self.department
         #pass
   
     @classmethod
     deffactory(self, name, function):
         if function == "Geek":
             return Geek(name)
         elif function == "hardware":
             return HardwareGeek(name)
         elif function == "technical manager":
             return TechnicalManager(name)
         elif function == "account manager":
             return AccountManager(name)
         else:
             raise ValueError("Unknown employee type")
         #return EmployeeFake(name)
   
   
class EmployeeFake(Employee):
     department = "circus"
     price = 15
   
   
class EmployeeHardware(Employee):
     department = "hardware"
     project_o = Project("installation of two PCs", "Lehman Brothers Bank")
     emp = "kim"
     det = {"MAC hardware purchase", "hardware configuration", "customer installation"}#"detail"
     hard = 0
     project_o.perform(emp, det, hard)
     detail = detail
   
class Geek(EmployeeHardware):
     price = 60
   
   
class HardwareGeek(EmployeeHardware):
     price = 0
   
     # function to move to the correct class
   
     def pricing_intel(self):
         self.price = 65
         return self.price
         # pass
   
     def pricing_mac(self):
   
         detail = {"MAC hardware purchase", "hardware configuration", "customer installation"}
         if detail == "MAC hardware purchase":
             self.price = 75
         if detail == "hardware configuration":
             self.price = 50
         elif detail == "customer installation":
             self.price = 50
         else:self.price = 75
    
class TechnicalManager(EmployeeHardware):
     price = 90
   
   
class AccountManager(Employee):
     department = "account"
     price = 100
   
   
   
if __name__ == '__main__':
     #
   
     #1)
     kim = Employee.factory("Kim", "hardware") # return HardwareGeek object
     ali = Employee.factory("Ali", "hardware") # return HardwareGeek object
     albert = Employee.factory("Albert", "technical manager") # return TechnicalManager object
     sophie = Employee.factory("Sophie", "account manager") # return AccountManager object
   
     #2)
     project_o = Project("installation of two PCs", "Lehman Brothers Bank")
   
     #3)
     project_o.perform(albert, "meeting with client", 1)
     kim.pricing_intel() # switch to "PC" pricing
     project_o.perform(kim, "PC hardware purchase", 0.5)
     kim.pricing_mac() # switch to "MAC" pricing
     project_o.perform(kim, "MAC hardware purchase", 1.5)
     project_o.perform(ali, "hardware configuration", 2)
     project_o.perform(ali, "customer installation", 3)
     project_o.perform(albert, "key delivery", 0.5)
     project_o.perform(sophie, "agreement with the client", 0.5)
   
     # we add expenses
     project_o.expense(kim, "two PCs and accessories", 1500)
     project_o.expense(kim, "three MACs and accessories", 4500)
   
     print(project_o)
   
     #4)
     print("CSV")
   
     project_it = iter(project_o)
     whileTrue:
         try:
             #iterate
             csv = next(project_it)
             print(csv)
         except StopIteration:
             # when all records have been received
             break
*thanks for the help*
Reply
#3
What is this supposed to do? What it does is set self.price = 75.
    def pricing_mac(self):
  
        detail = {"achat matériel MAC", "configuration matériel", "installation chez client"}
        if detail == "achat matériel MAC":
            self.price = 75
        if detail == "configuration matériel":
            self.price = 50
        elif detail == "installation chez client":
            self.price = 50
        else :self.price = 75    # <- This always executes
This makes a set:
detail = {"achat matériel MAC", "configuration matériel", "installation chez client"}
detail will never equal "achat matériel MAC" or "configuration matériel" or any other str. A set is never equal to a str.
Reply
#4
Bonjour,

it is really hard to understand what you intend to do without further explanation. You have a bunch of classes which only hold a class varIable and same classes which only overwrite an existing class variable. There are plenty of "code smells", which means that the design is probably overcomplicated or wrong structured and not too pythonic.

Any why do a lot of instance variables start with a double under score? I don't see a specific reason to use it here. In case this should be some type of protection: the instance variables still can be accessed, Python has nothing like "private variable".

So a bit more explanation what you intend to achieve would be good. Preferable in english language.

Regards, noisefloor
Reply
#5
I want to develop function pricing_intel() and pricing_mac(), which defines the price of each detail of employee who do , the price of intel material different from mac price
Gribouillis write Feb-19-2023, 07:32 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#6
(Feb-19-2023, 03:39 PM)Yoriz Wrote: Google translation
I think the original was already translated from another language than French.
Reply
#7
Hi,
(Feb-19-2023, 07:24 PM)sollarriiii Wrote: I want to develop function pricing_intel() and pricing_mac(), which defines the price of each detail of employee who do , the price of intel material different from mac price
I still don't get the point... As far as I can see, what you call "price" is some type of base price or factor. As the price is a class variable, you can simple overwrite it. Howerver, your quite complicated (most likely overcomplicated) class design and inheritance makes it extremly hard to trace where something is overwritten (or not).

Regards, noisefloor
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to get around recursive method call Skaperen 10 4,192 Jul-01-2020, 10:09 PM
Last Post: Skaperen
  How to call COM-method using comtypes jespersahner 0 2,388 Nov-15-2019, 12:54 PM
Last Post: jespersahner
  Polymorphism not working with a call to a abstract method colt 3 2,277 Nov-04-2019, 11:04 PM
Last Post: colt
  How to Call a method of class having no argument dataplumber 7 6,322 Oct-31-2019, 01:52 PM
Last Post: dataplumber
  Call method from another method within a class anteboy65 3 7,355 Sep-11-2019, 08:40 PM
Last Post: Larz60+
  What is the use of call method and when to use it? everyday1 1 3,269 Jul-14-2019, 01:02 PM
Last Post: ichabod801
  I'm trying to figure out whether this is a method or function call 357mag 2 2,381 Jul-04-2019, 01:43 AM
Last Post: ichabod801
  How to call a method in a module using code KingPieter 4 2,965 Jan-15-2019, 09:13 PM
Last Post: KingPieter
  call method in class using threads? masterofamn 0 2,672 Jan-24-2017, 09:09 PM
Last Post: masterofamn

Forum Jump:

User Panel Messages

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