您的位置:首页 > 编程语言 > Python开发

[基础] - Python中 @staticmethod 和 @classmethod

2015-11-27 15:43 791 查看

[基础] - Python中 @staticmethod 和 @classmethod

staticmethod 基本上和一个全局函数差不多,只不过可以通过类或类的实例对象来调用而已, 不会隐式地传入任何参数。这个和静态语言中的静态方法比较像。

classmethod 是和一个class相关的方法,可以通过类或类实例调用,并将该class对象隐式地当作第一个参数传入。类方法的第一个参数是cls,而实例方法的第一个参数是self。

class Person:
def __init__(self):
print "init"

@staticmethod
def sayHello(hello):
print "staticmethod"

@classmethod
def introduce(cls,hello):
cls.sayHello(hello)
print "classmethod"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: