关于classmethod

关于classmethod

刚学python不久,我写了个简单的类,是参考某个工程里的代码写的

[Copy to clipboard] [ - ]
CODE:
import MySQLdb
import config
class DB:
        DBuser = config.user
        DBpass = config.password
        DBdbname = config.dbname

        def connect(self):
                db = MySQLdb.connect(user = self.DBuser,passwd = self.DBpass,db = self.DBdbname)
                c = db.cursor()
                return(c)
        connect = classmethod(connect)

        def insert(self,name,age):
                c = self.connect()
                r = c.execute("""insert into table1 values ( '%s',%d)"""%(name,age))
                return(r)
        insert = classmethod(insert)

其中connect = classmethod(connect) 这句话是什么意思呢?我是看着原来的代码里有写,我也才写了。跑起来就是不行啊。删了之后貌似可以了

[Copy to clipboard] [ - ]
CODE:
[zdai@localhost python]$ python list.py
Traceback (innermost last):
  File "list.py", line 17, in ?
    class DB:
  File "list.py", line 26, in DB
    connect = classmethod(connect)
NameError: classmethod

能告诉我加上之后和没加到底有什么区别吗,我看原来的代码里每个方法都这么转换一下的。我查看了python的文档,
Decorators for Functions and Methods
Python 2.2 extended Python's object model by adding static methods and class methods, but it didn't extend Python's syntax to provide any new way of defining static or class methods. Instead, you had to write a def statement in the usual way, and pass the resulting method to a staticmethod() or classmethod() function that would wrap up the function as a method of the new type. Your code would look like this:
class C:
   def meth (cls):
       ...
   
   meth = classmethod(meth)   # Rebind name to wrapped-up class method

但看了之后也不是很理解啊。
最直接的理解就是class method可以直接用类名调用,像这样

[Copy to clipboard] [ - ]
CODE:
>>> class E(object):
     def f(klass, x):
          return klass.__name__, x
     f = classmethod(f)

>>> print E.f(3)
('E', 3)
>>> print E().f(3)
('E', 3)

http://users.rcn.com/python/download/Descriptor.htm#static-methods-and-class-methods