Adding attributes to instancemethods in Python

核能气质少年 提交于 2019-11-28 18:13:53

For attribute lookup, Python is automatically using the real function attached to the instance method for you.

For attribute setting, it is not.

They are two separate operations depending on which side of the statement you're on, even though they both use the . operator.

When you access an instance method's __func__, you're manually accessing the real function that actually has the moo attribute.

In Python 3 this will work as you would like / expect as methods are basically just functions.

If you are looking to modify the function attributes of both functions and instance methods from C then you have to check the type of callable you have.

So assuming you have a PyObject of some type of callable you can check it like this:

PyObject *callable;  // set to something callable
PyObject *setting;  // set to something
if(PyMethod_Check(callable)){
    PyObject_SetAttrString(PyMethod_Function(callable),"attribute",setting);
}else{
    PyObject_SetAttrString(callable,"attribute",setting);
}
...
// and the inverse
if(PyMethod_Check(callable){         
     if(PyObject_HasAttrString(PyMethod_Function(callable),"attribute")){
        PyObject_DelAttrString(PyMethod_Function(callable),"attribute");
     }
  }else{
     if(PyObject_HasAttrString(callable,"attribute")){
        PyObject_DelAttrString(callable,"attribute");
     }
  }  

Now the code agf pointed out works from within Python for instance methods. If I just try to set the attribute of the instance method it would not find the attribute no matter how I tried to access it from Python.

I ran into this issue and Li Haoyi's question with agf's answer helped me understand what needed to be changed. I figured someone will find this question and answer again while looking for how to solve this issue through C.

Edit: Note: This is for Python 2.7.x. Python 3.x uses different function calls.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!