Advertisement
Lyuben_Andreev

Functors

Aug 13th, 2024
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | Software | 0 0
  1. class UserPlayer:
  2.     def __init__(self, name):
  3.         self.name = name
  4.         self.wallet = 100
  5.         self.walletSetter = WalletFunctor()
  6.         self.wallet = self.walletSetter()
  7.  
  8.     def updateWallet(self, coins):
  9.         self.wallet += coins
  10.         self.wallet = self.walletSetter(coins)
  11.  
  12.     def showWallet(self):
  13.         print(f"You have {self.wallet} coins now.")
  14.         print(f"{self.name}! You have {self.wallet} coins now.")
  15.  
  16.  
  17. class WalletFunctor:
  18.     def __init__(self, startCoins=100):
  19.         self.__startCoins = startCoins
  20.  
  21.     def __call__(self, coins=0):
  22.         return self.__startCoins + coins
  23.  
  24.  
  25. user1 = UserPlayer("Joe")
  26. user1.updateWallet(50)
  27. user1.showWallet()
  28. userWallet = WalletFunctor()
  29. print(f"Start state of user wallet: {userWallet()} coins")
  30. print(f"State of user wallet after updating to 50 coins: {userWallet(50)} coins")
  31. botWallet = WalletFunctor(50)
  32. print(f"Start state of bot wallet: {botWallet()} coins")
  33. print(f"State of user bot after updating to 20 coins: {botWallet(20)} coins")
  34. user1 = UserPlayer("Joe")
  35. user1.showWallet()
  36. user1.updateWallet(50)
  37. user1.showWallet()
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement