Skip to content

Latest commit

 

History

History
51 lines (41 loc) · 1.22 KB

401-class-09.md

File metadata and controls

51 lines (41 loc) · 1.22 KB

Notes for Ten Thousand 4

Enriching Your Python Classes With Dunder (Magic, Special) Methods

What are Dunder Methods?

  • 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, for example init or str
  • adopted the term “dunder methods”, a short form of “double under”
  • sometimes called "magic methods"
  • let you emulate the behavior of built-in types

example to get length of string in class:

class LenSupport:
    def __len__(self):
        return 42

>>> obj = LenSupport()
>>> len(obj)
42

Tutorial: Basic Statistics in Python — Probability

  • at the most basic level, probability seeks to answer the question, “What is the chance of an event happening?” An event is some outcome of interest

example simulating coin flip:

import random
def coin_trial():
heads = 0
for i in range(100):
    if random.random() <= 0.5:
        heads +=1
    return heads
def simulate(n):
    trials = []
    for i in range(n):
        trials.append(coin_trial())
    return(sum(trials)/n)
simulate(10)
>>> 5.4
simulate(100)
>>> 4.83
simulate(1000)
>>> 5.055
simulate(1000000)
>>> 4.999781