https://m7madmomani2.github.io/reading-notes2
In Python, special methods are a set of predefined methods you can use to enrich your classes. They are easy to recognize because they start and end with double underscores,
example init or str.
Dunder methods let you emulate the behavior of built-in types. For example, to get the length of a string you can call len(‘string’). But an empty class definition doesn’t support this behavior out of the box.
Iteration: len, getitem, reversed In order to iterate over our account object I need to add some transactions. So first, I’ll define a simple method to add transactions. I’ll keep it simple because this is just setup code to explain dunder methods, and not a production-ready accounting system:
def add_transaction(self, amount):
if not isinstance(amount, int):
raise ValueError('please use int for amount')
self._transactions.append(amount)
class Account:
def __call__(self):
print('Start amount: {}'.format(self.amount))
print('Transactions: ')
for transaction in self:
print(transaction)
print('\nBalance: {}'.format(self.balance))
Throughout this article I will enrich a simple Python class with various dunder methods to unlock the following language features:
Initialization of new objects Object representation Enable iteration Operator overloading (comparison) Operator overloading (addition) Method invocation Context manager support (with statement)
1) Flipping a heads 2) Flipping a tails
The Z-score is a simple calculation that answers the question, “Given a data point, how many standard deviations is it away from the mean?
The equation below is the Z-score equation.