python 的花招,只要不考虑运行效率,主要就是
A. 玩那一堆 __xxxx__ 函数,
B. 下面几个自带的库
import ast
import inspect
import functools
import ctypes
C. 和这个函数 id()
A,B,C 基本可以让你为所欲为
# 破坏built-in 类
#谨慎使用
import inspect
import functools
import ctypes
class PyObject(ctypes.Structure):
class PyType(ctypes.Structure):
pass
ssize = ctypes.c_int64 if ctypes.sizeof(ctypes.c_void_p) == 8 else ctypes.c_int32
_fields_ = [
('ob_refcnt', ssize),
('ob_type', ctypes.POINTER(PyType)),
]
def incref(self):
self.ob_refcnt += 1
def decref(self):
self.ob_refcnt -= 1
def sign(klass,value):
class SlotsProxy(PyObject):
_fields_ = [('dict', ctypes.POINTER(PyObject))]
name = klass.__name__
target = klass.__dict__
proxy_dict = SlotsProxy.from_address(id(target))
namespace = {}
ctypes.pythonapi.PyDict_SetItem(
ctypes.py_object(namespace),
ctypes.py_object(name),
proxy_dict.dict,
)
namespace[name]["签名"] = value
# 修改 built-in str
sign(str,"某某人专用")
>>> "1234567".签名
'某某人专用'
>>>
>>> "abcde".签名.签名.签名.签名.签名.签名.签名
'某某人专用'
>>>
#土制 单参化
import inspect
import functools
def uargs(f):
arg_names = inspect.getfullargspec(f).args
def _func(arg_names,d):
args = []
for i in range(len(arg_names)):
#necessary for version < 3.5 to keep order
k = arg_names[i]
args.append(d[k])
return(f(*args))
func = functools.partial(_func,arg_names)
return(func)
def cufunc(a,b,c,d):
print(a,b,c,d)
myfunc = uargs(cufunc)
myfunc = uargs(cufunc)
myfunc({"a":100,"b":200,"c":300,"d":400})
100 200 300 400
# 土制 库里化
import inspect
import functools
class curry():
def goose():
def egg(*args):
egg.arguments.extend(args)
return(egg)
egg.__setattr__("arguments",[])
return(egg)
def __init__(self,orig_func):
params_count = inspect.getfullargspec(orig_func).args.__len__()
self.orig_func = orig_func
self.params_count = params_count
self.egg = goose()
def __call__(self,*args):
count = self.params_count
orig_func = self.orig_func
egg = self.egg
egg(*args)
args_lngth = len(egg.arguments)
if(args_lngth
return(self)
else:
args = egg.arguments
egg.arguments = []
return(orig_func(*args))
def __repr__(self):
return(self.egg.arguments.__repr__())
def cufunc(a,b,c,d):
print(a,b,c,d)
myfunc = curry(cufunc)
myfunc(10)
myfunc(20)
myfunc(30)(40)
#10 20 30 40
python 因为暴露了 id()函数 和ctypes,可以认为python里没有primitive 和native/built-in,也就意味着基本上你想做什么都可以