python 类中staticmethod,classmethod,普通方法

时间:2023-03-09 16:43:47
python 类中staticmethod,classmethod,普通方法

1.staticmethod:静态方法
和全局函数类似,但是通过类和对象调用。

2.classmethod:类方法
和类相关的方法,第一个参数是class对象(不是实例对象)。
在python中class也是一个真实存在于内存中的对象,不同于其他语言只存在于编译期间。

3.普通方法
和实例相关的方法,通过类实例调用。

4.代码示例

#coding:utf-8
'''
Created on 2015年5月29日
@author: canx
''' class Person:
def __init__(self):
print "init" @staticmethod
def sayHello(hello):
print "sayHell %s"%(hello) @classmethod
def introduce(cls,hello):
print "introduce %s"%(hello) def hello(self,hello):
print "hello %s"%(hello) def main():
Person.sayHello("test")
Person.introduce("test")
p=Person()
p.hello("test") if __name__=='__main__':
main()

输出结果:

python 类中staticmethod,classmethod,普通方法