Firstly, there is class A
with two class variables and two instance variables:
In [1]: def fun(x, y): return x + y
In [2]: class A:
...: cvar = 1
...: cfun = fun
...: def __init__(self):
...: self.ivar = 100
...: self.ifun = fun
We can see that both class variable and instance variable of int type works fine:
In [3]: a = A()
In [4]: a.ivar, a.cvar
Out[4]: (100, 1)
However, things have changed if we check the function type variables:
In [5]: a.ifun, a.cfun
Out[5]:
(<function __main__.fun>,
<bound method A.fun of <__main__.A instance at 0x25f90e0>>)
In [6]: a.ifun(1,2)
Out[6]: 3
In [7]: a.cfun(1,2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/future/<ipython-input-7-39aa8db2389e> in <module>()
----> 1 a.cfun(1,2)
TypeError: fun() takes exactly 2 arguments (3 given)
I known that python has translated a.cfun(1,2)
to A.cfun(a,1,2)
and then error raised.
My question is: Since both cvar
and cfun
are class variable, why do python treat them in difference way?