日版 D2C Key Wii 改版美版完美教程(持续更新)

Python 技巧:@classmethod 修饰符

K*K posted @ Thu, 05 Mar 2009 17:44:28 -0400 in 鼓鼓捣捣 with tags python programming , 943 readers
简单办法搞定 Linux 上蓝牙和 USB 线 GPRS 拨号上网。

通常情况下,如果我们要使用一个类的方法,那我们只能将一个类实体化成一个对象,进而调用对象使用方法。

比如:

class Hello(object):
    def __init__:
        ...

    def print_hello(self):
        print "Hello"

 要用 print_hello() 就得:

hlo = Hello()
hlo.print_hello()
Hello

如果用了 @classmethod 就简单了。

class Hello(object):
    def __init__:
        ...

    @classmethod
    def print_hello():
        print "Hello"

要用的话直接:

Hello.print_hello()
Hello

注意:@classmethod 仅仅适用于单独的,与类本身的数据结构无关函数,其实用了它的函数,与使用普通函数无异,甚至不能在参数里加入 self,如果要在其中使用类的数据结构,仍然需要将类实例化一次才可以,所以要小心使用。

 其实 Python 的 Decorator 非常有意思,更多可以去下面的网页参考一下:

http://www.python.org/dev/peps/pep-0318/


* Login
*

simple_captcha.jpg
(type the code from the image)