Created
April 22, 2017 21:31
-
-
Save Fuyukai/5e418936eaff9b9e34708fe21a91ab55 to your computer and use it in GitHub Desktop.
Bootleg classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
def gi(s, k): | |
try: | |
return s[k] | |
except KeyError: | |
raise AttributeError(k) from None | |
attrdict = type("attrdict", (dict,), {"__getattr__": gi, "__setattr__": dict.__setitem__}) | |
def method(d: attrdict): | |
def deco(func): | |
@functools.wraps(func) | |
def _inner(*args, **kwargs): | |
return func(d, *args, **kwargs) | |
d[func.__name__] = _inner | |
return func | |
return deco | |
def MyClass(constructor_arg): | |
body = attrdict() | |
@method(body) | |
def __init__(self): | |
# your constructor here | |
self.heck = constructor_arg | |
@method(body) | |
def something(self): | |
print(self.heck) | |
@method(body) | |
def what_the_fuck(self, a): | |
self.heck = a | |
self.something() | |
body["__init__"]() | |
return body | |
ins = MyClass(2) | |
ins.something() | |
ins.what_the_fuck(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment