热线电话:13121318867

登录
2018-12-03 阅读量: 795
类方法与静态方法是什么

类方法与静态方法

  • 类方法将cls作为第一个参数,而静态方法不需要特定的参数。
  • 类方法可以访问或修改类状态,而静态方法无法访问或修改它。
  • 通常,静态方法对类状态一无所知。它们是实用程序类型方法,它采用一些参数并处理这些参数。另一方面,类方法必须具有class作为参数。
  • 我们在python中使用@classmethod装饰器来创建一个类方法,我们使用@staticmethod装饰器在python中创建一个静态方法。

什么时候用?

  • 我们通常使用类方法来创建工厂方法。Factory方法为不同的用例返回类对象(类似于构造函数)。
  • 我们通常使用静态方法来创建实用程序函数。

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

要在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
5
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子