类方法与静态方法
什么时候用?
如何定义类方法和静态方法?
要在python中定义类方法,我们使用@classmethod装饰器来定义我们使用@staticmethod装饰器的静态方法。
让我们看一个例子来理解它们之间的区别。我们假设我们要创建一个Person类。现在,python不支持像C ++或Java那样的方法重载,所以我们使用类方法来创建工厂方法。在下面的示例中,我们使用类方法从出生年份创建人物对象。
如上所述,我们使用静态方法来创建效用函数。在下面的例子中,我们使用静态方法来检查一个人是否成年。
履行
# Python program to demonstrate
# use of class method and static method.
from datetime import date
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# a class method to create a Person object by birth year.
@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)
# a static method to check if a Person is adult or not.
@staticmethod
def isAdult(age):
return age > 18
person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)
print person1.age
print person2.age
# print the result
print Person.isAdult(22)
三个资料Q群下载不了也转发不了,先放这里Fine_tuning.zipLangChain.zipdata_clear.rar