Python Forum
using mutable in function defintion as optional paramter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
using mutable in function defintion as optional paramter
#9
(Apr-27-2024, 04:57 PM)Pedroski55 Wrote: Is there a good reason why we should not pass the dictionary we want modified by name?
Can do something like this,but think how this solution would look if adding more shopping list.
Then have to make dictionary's global eg clothes_shop_list = {}, hardware_store = {} and add to them.
Also a ordinary class make more sense for this,if not familiar with @dataclass.
class ShoppingList:
    def __init__(self, name):
        self.name = name
        self.items = {}

    def add_item(self, item_name, quantity):
        if item_name in self.items:
            self.items[item_name] += quantity
        else:
            self.items[item_name] = quantity

    def show_list(self):
        print(f"{self.name} Shopping List:")
        for item, quantity in self.items.items():
            print(f"{quantity} x {item}")
        print("-" * 25)

# Create separate shopping list objects with names
clothes_list = ShoppingList("Clothes")
electronics_list = ShoppingList("Electronics")
# Add items to each shopping list
clothes_list.add_item('T-shirt', 5)
clothes_list.add_item('Jeans', 2)
electronics_list.add_item('USB cable', 3)
electronics_list.add_item('Headphones', 1)
# Display each shopping list
clothes_list.show_list()
electronics_list.show_list()
Output:
Clothes Shopping List: 5 x T-shirt 2 x Jeans ------------------------- Electronics Shopping List: 3 x USB cable 1 x Headphones -------------------------
akbarza and Pedroski55 like this post
Reply


Messages In This Thread
RE: using mutable in function defintion as optional paramter - by snippsat - Apr-27-2024, 09:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  mutable argument in function definition akbarza 1 566 Dec-15-2023, 02:00 PM
Last Post: deanhystad
  mutable values to string items? fozz 15 3,174 Aug-30-2022, 07:20 PM
Last Post: deanhystad
  "'DataFrame' objects are mutable, thus they cannot be hashed" Mark17 1 6,992 Dec-25-2020, 02:31 AM
Last Post: tinh
  Mutable Strings millpond 3 2,714 Aug-24-2020, 08:42 AM
Last Post: millpond
  What is the meaning of mutable data type? qliu 3 3,080 Apr-17-2020, 07:20 PM
Last Post: deanhystad
  copying parts of mutable sequences Skaperen 1 2,307 Dec-02-2019, 10:34 AM
Last Post: Gribouillis
  A mutable string?? silentknight85 5 4,822 May-31-2019, 10:11 AM
Last Post: silentknight85
  Trouble making an argument optional linuxnoob 2 3,006 Aug-31-2018, 01:52 AM
Last Post: linuxnoob
  compacting a mutable sequence Skaperen 6 4,573 Jan-23-2018, 03:54 AM
Last Post: Skaperen
  Paramter lists when shift+tab doesn't work sobrio1 0 3,222 Oct-15-2017, 03:41 PM
Last Post: sobrio1

Forum Jump:

User Panel Messages

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