类方法:
使用@classmrthod修饰器定义的,类方法是将本身作为对象进行操作的方法。
静态方法:
无需实例参与即可调用的方法,静态方法使用@staticmethod装饰器来声明。
class Person:
name = "jack"
def __init__(self,name):
self.name = name
def tell(self):
print(self.name)
@classmethod
def say(cls):
print(cls.name)
@staticmethod
def talk():
print(Person.name)
if __name__ == '__main__':
p = Person("rose")
p.tell()
Person.say()
Person.talk()
F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day5/类方法和静态方法.py
rose
jack
jack
Process finished with exit code 0
@classmethod和@staticmethod的区别:
使用@classmethod的时候,我们可以不知道类的名字是什么即可以调用;而@staticmethod不一样,在使用@staticmethod的时候,我们必须事先知道类的名字是什么才能够去使用。
class Date:
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
# @staticmethod
# def get_date(string_date):
# year,month,day = string_date.split("-")
# date = Date(year,month,day)
# return date
@classmethod
def get_date(cls,string_date):
year,month,day = string_date.split("-")
date = cls(year,month,day)
return date
def out_date(self):
print("year:",self.year)
print("month:", self.month)
print("day:", self.day)
if __name__ == '__main__':
t = Date.get_date("2019-3-24")
t.out_date()
F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day5/类方法和静态方法2.py
year: 2019
month: 3
day: 24
Process finished with exit code 0