Skip to content

Instantly share code, notes, and snippets.

>>> class Integer:
... def __init__(self, name):
... self.name = name
... def __get__(self, instance, cls):
... return instance.__dict__[self.name]
... def __set__(self, instance, value):
... if not isinstance(value, int):
... raise TypeError('Expected int')
... instance.__dict__[self.name] = value
...
>>> class Foo:
... def __init__(self, x):
... self.x = x
... def __setattr__(self, name, value):
... if name not in {'x'}:
... raise AttributeError('only x is allowed')
... super().__setattr__(name, value)
...
>>> f = Foo(2)
>>> f.x
>>> class Foo:
... def upper(self, value):
... print(value.upper())
...
>>> class Bar:
... def __init__(self):
... self.foo = Foo()
... def __getattr__(self, name):
... return getattr(self.foo, name)
...
>>> import time
>>> def after(seconds, func):
... time.sleep(seconds)
... func()
...
>>> def hello():
... print('hello world')
...
>>> def greet(name):
... print(f'hello {name}')
>>> def func(x, y, z):
... print(x, y, z)
...
>>> func(1, 2, 3)
1 2 3
>>> func(1, z=3, y=2)
1 2 3
>>> def func(x, *args):
... print(x)
... print(args)
>>> '''
... build quiz game with users
...
... Users
...
... Name: alice
... Score: 3
...
... Name: bob
... Score: 6
>>> def tensquared():
... return 10 * 10
...
>>> tensquared()
100
>>> def ninesquared():
... return 9 * 9
...
>>> ninesquared()
81
>>> def add(x, y):
... return x+y
...
>>> add(2,3)
5
>>>
>>> a = lambda : add(2,3)
>>> a
<function <lambda> at 0x7f95b61a0ae8>
>>> a()
>>> def boo(func):
... def wrapper(*args, **kwargs):
... print('BOO')
... return func(*args, **kwargs)
... return wrapper
...
>>> def add(x, y):
... return x + y
...
>>> add = boo(add)
>>> def boo_what(fmt):
... def boo(func):
... def wrapper(*args, **kwargs):
... print(f'BOO {fmt}')
... return func(*args, **kwargs)
... return wrapper
... return boo
...
>>> @boo_what('hello')
... def add(x, y):