am_dot_com

IA 2022-11-02

Nov 2nd, 2022 (edited)
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. # 1.py
  2. # let us understand OOP in Python
  3. # a bit of numpy and its "choice" function
  4.  
  5. import numpy as np
  6.  
  7. class MyDataTypeForPlayingWithRandomness:
  8.  
  9. def __init__(
  10. self,
  11. pName="Default name",
  12. pColOfThings:list=[]
  13. ):
  14. # pass # no initialization
  15. self.mName = pName
  16. self.mCol = pColOfThings
  17. # def __init__
  18.  
  19. def __str__(self):
  20. memoryCell = id(self)
  21. strMsg = "-"*60+"\n"
  22. strMsg += f"My name is {self.mName}\n"
  23. strMsg += "Hello, I am an object of data type MyDataTypeForPlayingWithRandomness\n"
  24. strMsg += f"I live at memory cell {memoryCell}\n"
  25. strMsg += f"My collection is: {self.mCol}\n"
  26. return strMsg
  27. # def __str__
  28.  
  29. def someNormalBehavior(self):
  30. print(f"Hello from {self.mName}")
  31. # def someNormalBehavior
  32.  
  33. def getRandomEntryFromTheCollection(self):
  34. somethingRandom = np.random.choice(
  35. self.mCol
  36. )
  37. return somethingRandom
  38. # def getRandomEntryFromTheCollection
  39.  
  40. # class MyDataTypeForPlayingWithRandomness
  41.  
  42. r1 = MyDataTypeForPlayingWithRandomness("R ONE")
  43.  
  44. print(r1) # to request NO behavior
  45. # equivalent
  46. print(r1.__str__()) # is to request the "to string" behavior
  47.  
  48. r2 = MyDataTypeForPlayingWithRandomness("R TWO")
  49. print(r2)
  50.  
  51. r3 = MyDataTypeForPlayingWithRandomness()
  52. print(r3)
  53.  
  54. r3 = MyDataTypeForPlayingWithRandomness("XPTO")
  55. print(r3)
  56.  
  57. r1.someNormalBehavior()
  58.  
  59. r4 = MyDataTypeForPlayingWithRandomness(
  60. "The one who has a collection",
  61. [10, 20, 30]
  62. )
  63. print (r4.getRandomEntryFromTheCollection())
  64.  
  65. r5 = MyDataTypeForPlayingWithRandomness(
  66. "The fruit collector",
  67. ["banana", "strawberry", "peaches", "watermelon"]
  68. )
  69. print("A random fruit: "+\
  70. r5.getRandomEntryFromTheCollection()
  71. )
Advertisement
Add Comment
Please, Sign In to add comment