Python中的类方法与静态方法


Python中的类方法是一种绑定到类而不是类对象的方法。静态方法也类似,但它们之间存在一些基本差异。对于类方法,我们需要指定`@classmethod`装饰器;对于静态方法,则使用`@staticmethod`装饰器。

类方法语法。

class my_class:
   @classmethod
  deffunction_name(cls, arguments):
      #Function Body
      return value

静态方法语法。

class my_class:
   @staticmethod
   deffunction_name(arguments):
      #Function Body
      return value

类方法和静态方法之间有什么区别?

类方法 静态方法
类方法以`cls`(类)作为第一个参数。 静态方法不接受任何特定参数。
类方法可以访问和修改类状态。 静态方法不能访问或修改类状态。
类方法将类作为参数来了解该类的状态。 静态方法不知道类状态。这些方法用于通过一些参数执行一些实用程序任务。
此处使用`@classmethod`装饰器。 此处使用`@staticmethod`装饰器。

静态方法用于执行一些实用程序任务,而类方法用于工厂方法。工厂方法可以为不同的用例返回类对象。

示例代码

from datetime import date as dt
class Employee:
   def __init__(self, name, age):
      self.name = name
      self.age = age
   @staticmethod
   defisAdult(age):
      if age > 18:
         return True
      else:
         return False
   @classmethod
   defemp_from_year(emp_class, name, year):
      return emp_class(name, dt.today().year - year)
   def __str__(self):
      return 'Employee Name: {} and Age: {}'.format(self.name, self.age)
e1 = Employee('Dhiman', 25)
print(e1)
e2 = Employee.emp_from_year('Subhas', 1987)
print(e2)
print(Employee.isAdult(25))
print(Employee.isAdult(16))

输出

Employee Name: Dhiman and Age: 25
Employee Name: Subhas and Age: 31
True
False

更新于:2019年7月30日

19K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.