普通类方法
在Python中,通常我们调用某个类的方式,首先要实例化一个对象才能调用该类的方法,比如:
# _*_ coding:utf-8 _*_
class People:
def hello(self):
print("hello, Everyone.")
# 实例化一个对象
LiMing = People()
LiMing.hello()
"""""""""""""""""""""
输出:hello everyone
"""""""""""""""""""""
使用@staticmethod 和@classmethod 方法修饰
当我们使用@staticmethod 和@classmethod 修饰后,则不需要实例化就可以直接调用类方法,下面举例说明:
# _*_ coding:utf-8 _*_
class People:
def hello(self):
print("hello, Everyone.")
@staticmethod
def say_morning():
print("good morning")
@classmethod
def say_afternoon(cls):
print("good afternoon")
# 实例化一个对象
LiMing = People()
LiMing.hello()
# 使用@staticmethod 或者使用@classmethod 不需要实例化就可以直接调用类方法
People.say_morning()
People.say_afternoon()
"""""""""""""""""""
这里是输出:
hello, Everyone.
good morning
good afternoon
"""""""""""""""""""
self和cls以及@staticmethod 和@classmethod修饰的区别
使用@staticmethod 和@classmethod 都不需要实例化就可以直接调用类方法,但是两者还是有区别的,我们知道:
@staticmethod:不需要表示对象的self和自身类的clas参数,就和使用函数一样
@classmethod:不需要self,但第一个参数需要是表示自身类的cls参数。
使用表示自身的cls参数之后,@classmethod装饰的函数就可以使用类本身的方法。下面我们举例进行说明:
# _*_ coding:utf-8 _*_
class People:
def hello(self):
print("hello, Everyone.")
@staticmethod
def say_morning():
print("good morning")
# print(People.hello()) 这里会报错!
@classmethod
def say_afternoon(cls):
print("good afternoon")
print(cls().hello())
# 实例化一个对象
LiMing = People()
LiMing.hello()
People.say_morning()
People.say_afternoon()
"""""""""""""""""""
这里是输出:
hello, Everyone.
good morning
good afternoon
hello, Everyone.
"""""""""""""""""""