热线电话:13121318867

登录
2019-06-25 阅读量: 508
如何定义类方法和静态函数?

如何定义类方法和静态函数?

要在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)

0.0000
2
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子