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
Classmethod和StaticMehtod有什么区别?
静态方法用于执行一些实用程序任务,而类方法用于工厂方法。工厂方法可以返回不同用例的类对象。
范例程式码
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