Skip to content

Commit fd43729

Browse files
author
tuntun
committed
Python中的类方法和静态方法
1 parent 2747c35 commit fd43729

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

cls.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,19 @@ def foo(cls):
1313
demo.foo()输出的结果跟dir(demo)的结果一样:
1414
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof_
1515
_', '__str__', '__subclasshook__', '__weakref__', 'foo']
16+
17+
classmethod:类方法
18+
staticmethod:静态方法
19+
20+
在python中,静态方法和类方法都是可以通过类对象和类对象实例访问。但是区别是:
21+
22+
1.@classmethod 是一个函数修饰符,它表示接下来的是一个类方法,而对于平常我们见到的则叫做实例方法。
23+
类方法的第一个参数cls,而实例方法的第一个参数是self,表示该类的一个实例。
24+
25+
2.普通对象方法至少需要一个self参数,代表类对象实例
26+
27+
3.类方法有类变量cls传入,从而可以用cls做一些相关的处理。并且有子类继承时,调用该类方法时,传入的类变量cls是子类,而非父类。
28+
对于类方法,可以通过类来调用,就像C.f(),有点类似C++中的静态方法, 也可以通过类的一个实例来调用,就像C().f(),这里C(),写成这样之后它就是类的一个实例了。
29+
30+
4.静态方法则没有,它基本上跟一个全局函数相同,一般来说用的很少
1631
"""

0 commit comments

Comments
 (0)