0

I'm trying to make a call to several functions dinamically. I can do it if this methods are publics but when I make this methods private doesn't work the same code.

I'm trying to call these functions dinamically:

def __total_voucher(self, quantity):
    return quantity

def __total_tshirt(self, quantity):
    return quantity

def __total_mug(self, quantity):
    return quantity

And the method from where I try to make a call dynamically to that methods are:

def total(self):
    total = 0
    for item in self.list_products:
        function = "__total_%s" % item.lower()
        if item in self.cart:
            total += getattr(self, function)(self.cart[item])
    return total

When I run the method "total" I've got this error:

  File "/home/josecarlos/Workspace/python/CofiCodeChallenge/checkout.py", line 56, in total
    total += getattr(self, function)(self.cart[item])
AttributeError: 'CheckOut' object has no attribute '__total_voucher'

What am I doing wrong? How can I make a call to private functions in Python?

José Carlos
  • 2,850
  • 12
  • 59
  • 95
  • What are you trying to do? i.e. why do you want to call these functions dynamically? also, are you sure you want two leading underscores? Regular python private function would just have 1. Removing the second underscore might your code work, but I would question your design before continuing as this seems like a bad idea. – Dan Dec 09 '20 at 16:07
  • 4
    Does this answer your question? [What is the meaning of single and double underscore before an object name?](https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-single-and-double-underscore-before-an-object-name) TL;DR you need `function = "_classname__total_%s" % item.lower()` – Tomerikoo Dec 09 '20 at 16:07

0 Answers0