python 类的内置方法_python内置类型的扩展方法

可以使用以下非常聪明的模块在纯Python中完成此操作:

[HTTPS://皮衣皮.Python.org/皮衣皮/forbidden fruit]

例如:

import functools

import ctypes

import __builtin__

import operator

class PyObject(ctypes.Structure):

pass

Py_ssize_t = hasattr(ctypes.pythonapi, 'Py_InitModule4_64') and ctypes.c_int64 or ctypes.c_int

PyObject._fields_ = [

('ob_refcnt', Py_ssize_t),

('ob_type', ctypes.POINTER(PyObject)),

]

class SlotsPointer(PyObject):

_fields_ = [('dict', ctypes.POINTER(PyObject))]

def proxy_builtin(klass):

name = klass.__name__

slots = getattr(klass, '__dict__', name)

pointer = SlotsPointer.from_address(id(slots))

namespace = {}

ctypes.pythonapi.PyDict_SetItem(

ctypes.py_object(namespace),

ctypes.py_object(name),

pointer.dict,

)

return namespace[name]

def die(message, cls=Exception):

"""

Raise an exception, allows you to use logical shortcut operators to test for object existence succinctly.

User.by_name('username') or die('Failed to find user')

"""

raise cls(message)

def unguido(self, key):

"""

Attempt to find methods which should really exist on the object instance.

"""

return functools.partial((getattr(__builtin__, key, None) if hasattr(__builtin__, key) else getattr(operator, key, None)) or die(key, KeyError), self)

class mapper(object):

def __init__(self, iterator, key):

self.iterator = iterator

self.key = key

self.fn = lambda o: getattr(o, key)

def __getattribute__(self, key):

if key in ('iterator', 'fn', 'key'): return object.__getattribute__(self, key)

return mapper(self, key)

def __call__(self, *args, **kwargs):

self.fn = lambda o: (getattr(o, self.key, None) or unguido(o, self.key))(*args, **kwargs)

return self

def __iter__(self):

for value in self.iterator:

yield self.fn(value)

class foreach(object):

"""

Creates an output iterator which will apply any functions called on it to every element

in the input iterator. A kind of chainable version of filter().

E.g:

foreach([1, 2, 3]).__add__(2).__str__().replace('3', 'a').upper()

is equivalent to:

(str(o + 2).replace('3', 'a').upper() for o in iterator)

Obviously this is not 'Pythonic'.

"""

def __init__(self, iterator):

self.iterator = iterator

def __getattribute__(self, key):

if key in ('iterator',): return object.__getattribute__(self, key)

return mapper(self.iterator, key)

def __iter__(self):

for value in self.iterator:

yield value

proxy_builtin(list)['foreach'] = property(foreach)

import string

print string.join([1, 2, 3].foreach.add(2).str().add(' cookies').upper(), ', ')

>>> 3 COOKIES, 4 COOKIES, 5 COOKIES

在那里,感觉不舒服吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值