File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11# 类方法和静态方法
22
3+ 在讲类方法和静态方法之前,先来看一个简单的例子:
4+
5+ ``` python
6+ class A (object ):
7+ def foo (self ):
8+ print ' Hello ' , self
9+
10+ >> > a = A()
11+ >> > a.foo()
12+ Hello, < __main__.A object at 0x 10c37a450>
13+ ```
14+
15+ 在上面,我们定义了一个类 A,它有一个方法 foo,然后我们创建了一个对象 a,并调用方法 foo。
16+
17+ ## 类方法
18+
19+ 如果我们想通过类来调用方法,而不是通过实例,那应该怎么办呢?
20+
21+ Python 提供了 ` classmethod ` 装饰器让我们实现上述功能,看下面的例子:
22+
23+ ``` python
24+ class A (object ):
25+ bar = 1
26+ @ classmethod
27+ def class_foo (cls ):
28+ print ' Hello, ' , cls
29+ print cls .bar
30+
31+ >> > A.class_foo() # 直接通过类来调用方法
32+ Hello, < class ' __main__.A' >
33+ 1
34+ ```
35+
36+ 在上面,我们使用了 ` classmethod ` 装饰方法 ` class_foo ` ,它就变成了一个类方法,` class_foo ` 的参数是 cls,代表类本身,当我们使用 ` A.class_foo() ` 时,cls 就会接收 A 作为参数。另外,被 ` classmethod ` 装饰的方法由于持有 cls 参数,因此我们可以在方法里面调用类的属性、方法,比如 ` cls.bar ` 。
37+
38+ ## 静态方法
39+
40+ 在类中往往有一些方法跟类有关系,但是又不会改变类和实例状态的方法,这种方法是** 静态方法** ,我们使用 ` staticmethod ` 来装饰,比如下面的例子:
41+
42+ ``` python
43+ class A (object ):
44+ bar = 1
45+ @ staticmethod
46+ def static_foo ():
47+ print ' Hello, ' , A.bar
48+
49+ >> > a = A()
50+ >> > a.static_foo()
51+ Hello, 1
52+ >> > A.static_foo()
53+ Hello, 1
54+ ```
55+
56+ 可以看到,静态方法没有 self 和 cls 参数,可以把它看成是一个普通的函数,我们当然可以把它写到类外面,但这是不推荐的,因为这不利于代码的组织和命名空间的整洁。
57+
58+ # 小结
59+
60+ - 类方法使用 ` @classmethod ` 装饰器,可以使用类(也可使用实例)来调用方法。
61+ - 静态方法使用 ` @staticmethod ` 装饰器,它是跟类有关系但在运行时又不需要实例和类参与的方法,可以使用类和实例来调用。
62+
63+
You can’t perform that action at this time.
0 commit comments