猴子在Python中修补C扩展

时间:2012-03-27 05:40:24

标签: python psycopg2 monkeypatching python-c-extension python-extensions

使用question 972中讨论的方法,我无法在psycopg中修补cursor()方法:

尝试使用类型在psycopg2中修补一个方法,但它不起作用:

>>> import psycopg2, types
import psycopg2, types
>>> db = psycopg2.connect('dbname=foo')
db = psycopg2.connect('dbname=foo')
>>> def mycursor(self):
def mycursor(self):
...     db.rollback()
    db.rollback()
...     return self.cursor()
    return self.cursor()
... 

>>> db.mycursor = types.MethodType(mycursor, db)
db.mycursor = types.MethodType(mycursor, db)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'psycopg2._psycopg.connection' object has no attribute 'mycursor'
>>> 

是因为它是C扩展吗?

1 个答案:

答案 0 :(得分:3)

正确。 C中定义的类型不能添加任意属性。