Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 1.py
- # let us understand OOP in Python
- # a bit of numpy and its "choice" function
- import numpy as np
- class MyDataTypeForPlayingWithRandomness:
- def __init__(
- self,
- pName="Default name",
- pColOfThings:list=[]
- ):
- # pass # no initialization
- self.mName = pName
- self.mCol = pColOfThings
- # def __init__
- def __str__(self):
- memoryCell = id(self)
- strMsg = "-"*60+"\n"
- strMsg += f"My name is {self.mName}\n"
- strMsg += "Hello, I am an object of data type MyDataTypeForPlayingWithRandomness\n"
- strMsg += f"I live at memory cell {memoryCell}\n"
- strMsg += f"My collection is: {self.mCol}\n"
- return strMsg
- # def __str__
- def someNormalBehavior(self):
- print(f"Hello from {self.mName}")
- # def someNormalBehavior
- def getRandomEntryFromTheCollection(self):
- somethingRandom = np.random.choice(
- self.mCol
- )
- return somethingRandom
- # def getRandomEntryFromTheCollection
- # class MyDataTypeForPlayingWithRandomness
- r1 = MyDataTypeForPlayingWithRandomness("R ONE")
- print(r1) # to request NO behavior
- # equivalent
- print(r1.__str__()) # is to request the "to string" behavior
- r2 = MyDataTypeForPlayingWithRandomness("R TWO")
- print(r2)
- r3 = MyDataTypeForPlayingWithRandomness()
- print(r3)
- r3 = MyDataTypeForPlayingWithRandomness("XPTO")
- print(r3)
- r1.someNormalBehavior()
- r4 = MyDataTypeForPlayingWithRandomness(
- "The one who has a collection",
- [10, 20, 30]
- )
- print (r4.getRandomEntryFromTheCollection())
- r5 = MyDataTypeForPlayingWithRandomness(
- "The fruit collector",
- ["banana", "strawberry", "peaches", "watermelon"]
- )
- print("A random fruit: "+\
- r5.getRandomEntryFromTheCollection()
- )
Advertisement
Add Comment
Please, Sign In to add comment