2017-02-22 110 views
2

有没有办法让猴子补丁的核心python类? 东西沿着线:有没有办法让猴子补丁的核心python类?

class Boo: 
    def is_empty(self) : return not self 

list.is_empty = Boo.is_empty 

TypeError: can't set attributes of built-in/extension type 'list'

我不想把它扩大,我想猴子修补它。


对不起,我的意思是“猴子补丁”。

+5

你说的“管型”是什么意思?你的意思是“猴子补丁”吗?如果是这样,不,你不能那样做。 – kindall

+1

@ kindall:我认为这是* duck-type *和* duct tape *之间的混合。 –

+0

如果你认为猴子补丁是可能的,但你必须很好地理解CPython的内部结构:https://gist.github.com/mahmoudimus/295200 –

回答

3

如果你指的monkey patching代替duck typing,那么,你可以用​​做得一样@ juanpa.arrivillaga在评论中建议:https://gist.github.com/mahmoudimus/295200

但即使如此,我会强烈建议反对它,因为它可以如果他们导入你的模块,会破坏其他人的代码。想象一下,如果每个人都在开始搞乱内部结构,你将无法安全地导入任何东西!

你应该做的却是继承的Python类:

class Boo(list): 
    def is_empty(self): 
     return not self 

>>> my_list = Boo([1, 2, 3, 4, 5]) 
>>> my_list2 = Boo([]) 
>>> my_list.is_empty() 
False 
>>> my_list2.is_empty() 
True 
>>> my_list2.append(5) 
>>> my_list2.is_empty() 
False 
>>> my_list2 
[5]