-1

If we have a class that has an instance e.g self.hawaii = 122, where the key is the pizza type and the value is the stock, how can I reduce the stock value (by 22) after an "input/order" from another class?


# Dummy example
class Pizza:
    def __init__(self):
        # key: pizza_type
        # value: stock available
        
        self.hawaii = 122
        self.funghi = 33
        
class Order(Pizza):

    def order(self):
        
        # For simplicity, I didn't use "input()"
        order_type = "hawaii"
        order_quantity = 22
        
        for i, j in super().__dict__.items():
            if i == order_type:
                print(j)
                j -= order_quantity
                print(j)
                
        for l in super().__dict__.items():
            print(l)
    
if __name__ == '__main__':
    b = Order()
    b.order()  

Output:

122
100
('hawaii', 122) ---> stays the same, I need 100 here
('funghi', 33)

Disclosure: I'm new to OOP.

I tried:
- self.get(order_type) --> Error
- self.order_type -->  Error
martineau
  • 119,623
  • 25
  • 170
  • 301
Samantha
  • 65
  • 1
  • 2
  • 7
  • If you want to change the value of an instance you will need to first create one — i.e. `p = Pizza()`, only then will you have something to modify. You will also have to pass it as an argument to the `order()` method of the instance of the other class. – martineau May 15 '21 at 15:25
  • Your use of classes seems convoluted. Classes and subclasses express an "is a" relationship, which doesn't make sense with your setup. Why is "a Pizza" some "stock of pizza*s*"? Why is an order a pizza, or even why is an order some *stock* of *pizzas*? It seems as if Order should just be a regular function, with the stock just being a dict. Alternatively, just have a stock that *consists of* a dict (not abusing its own `__dict__`) and has `order` as a method that *directly* accesses the stock by key. – MisterMiyagi May 15 '21 at 15:28

1 Answers1

1

When you assign the correct value to j at j -= order_quantity. But j was only a copy of self.hawaii so you have not changed the member value.

Anyway, scanning the __dict__ member only makes sense in very specific use cases. Here a more Pythonic way would be:

setattr(self, order_type, getattr(self, order_type) - order_quantity)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252