What is the difference between class variables of different types?

First, there is a class Awith 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 see that the class variable and the instance variable of type int work fine:

In [3]: a = A()

In [4]: a.ivar, a.cvar
Out[4]: (100, 1)

However, everything has changed if we check the variables of the function type:

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 knew what python translated a.cfun(1,2)into A.cfun(a,1,2)and then raised an error.

My question is : since both cvarand cfunis a class variable, why python handles them in different ways?

+5
source share
1 answer

In fact, the function assigned to the class member remains a function:

def x():pass

class A:  
    f = x
    e = None
    g = None

print(A.__dict__['f'])
# <function x at 0x10e0a6e60>

It is converted on the fly to a method object when you retrieve it from an instance:

print(A().f)
# <bound method A.x of <__main__.A instance at 0x1101ddea8>>

http://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy " ":

(, ), , method object... , (unbound bound) , .

, , . , Python 3, Class.fun , " ".

, , , ( "self" ). , - . . , javascript:

  myListener = new Listener()
  something.onSomeEvent = myListener.listen // won't work!
  something.onSomeEvent = function() { myListener.listen() } // works

Python :

  myListener = Listener()
  something.onSomeEvent = myListener.listen // works

, "" "" :

  def __init__(..., dir, ..):
       self.strip = str.lstrip if dir == 'ltr' else str.rstrip
       ...
  def foo(self, arg):
       self.strip(arg)

( vars = > , vars = > ) .

, python, , .. , .

+3

All Articles