Python 类方法 (classmethod)

与静态方法不同,Python 中的类方法绑定到一个类。因此,我们不必创建实例或对象来调用此类方法。类方法将 `cls` 作为隐式的第一个参数接收,就像标准方法将 `self` 作为第一个参数接收一样。这个 `cls` 允许您访问实例的类变量、方法和静态方法。

您可以使用 Python 编程语言的 `@classmethod` 装饰器或 `classmethod()` 函数来定义任何方法。两种方式都有效,但始终建议选择第一种方式。类方法的定义语法是

Class A:
    @classmethod
    def function_name(cls, arg1, arg2,....):
         ........
         ......

您可以使用 `类名.方法名` 或 `类名().方法名()` 调用类方法。两种方式都会返回结果。在本节中,我们将通过示例展示如何使用 `@classmethod` 装饰器和 `classmethod()` 函数在此编程语言中创建或定义类方法。

使用装饰器的 Python 类方法

在此示例中,我们使用 `@classmethod` 装饰器创建了一个名为 `message` 的类方法。在此方法中,`cls.__name__` 返回名称(Employee),`cls.company` 返回变量 `company` 的值(Tutorial Gateway)。

class Employee:
 
    company = 'Tutorial Gateway'
 
    @classmethod
    def message(cls):
        print('The Message is From %s' %cls.__name__)
        print('The Company Name is %s' %cls.company)
 
Employee.message()
 
print('-----------')
Employee().message() # Other way of calling
The Message is From Employee
The Company Name is Tutorial Gateway
-----------
The Message is From Employee
The Company Name is Tutorial Gateway

使用函数创建类方法

这里,我们使用 `classmethod()` 函数来创建类方法。从下面的 Python 代码中,`Employee.printValue` 语句将函数转换为类方法。

class Employee:
 
    value = 100
 
    def printValue(cls):
        print('The Value = %d' %cls.value)
 
Employee.printValue = classmethod(Employee.printValue)
Employee.printValue()
The Value = 100

从 Python 类方法调用静态方法

在此类方法示例中,我们展示了如何在类方法中调用 静态方法。这里,我们创建了一个名为 `func_msg()` 的静态方法,它打印一条欢迎消息。接下来,我们定义了返回类变量 `company` 和名称的 `message` 方法。在同一个函数中,我们使用 `cls.方法名` 调用静态方法。

class Employee:

    company = 'Tutorial Gateway'
 
    @classmethod
    def message(cls):
        print('The Company Name is %s' %cls.company)
        print('The Message is From %s Class' %cls.__name__)
        cls.func_msg()
 
    @staticmethod
    def func_msg():
        print("Welcome to Python Programming")
  
Employee.message()
Python classmethod Example

这里,我们不是打印消息,而是查找总和和平均值。首先,我们创建了一个接受三个参数并返回这三个参数之和的静态方法。接下来,我们定义了一个 Python 类方法,它使用 `cls` 调用静态方法。在函数内部,它返回静态方法结果的平均值。

class Employee:
 
    company = 'Tutorial Gateway'
 
    @staticmethod
    def add(a, b, c):
        return a + b + c

    @classmethod
    def avg(cls):
        x = cls.add(10, 20, 40)
        return (x / 3)
  
average = Employee.avg()
print('The Average Of three Numbers = ', average)
The Average Of three Numbers =  23.333333333333332

使用类方法更改类变量

在此示例中,我们将创建一个类方法,该方法接受一个参数并将值分配给变量。这意味着当您调用此函数时,它会将 `company` 文本替换为您作为参数值提供的新文本。这有助于隐藏变量并允许最终用户使用它们。

class Employee:
 
    company = 'Tutorial Gateway'
 
    @classmethod
    def func_newName(cls, new_Name):
        cls.company = new_Name
  
emp = Employee()

print(Employee.company)
print(emp.company)

print('----------')
Employee.func_newName('Coding')
 
print(Employee.company)
print(emp.company)
Tutorial Gateway
Tutorial Gateway
----------
Coding
Coding

Python 类方法实时示例

例如,如果客户端以长字符串的形式接收员工信息,并且详细信息由 `-`(或任何其他分隔符)分隔。与其从客户端执行拆分操作,我们可以创建一个类方法并允许他们使用该类方法。

在此示例中,我们初始化了 `fullname`、`age`、`gender` 和 `salary`。接下来,我们创建了一个类方法,它根据 `-` 分割给定的字符串并返回这些值。我建议您参考 字符串分割 文章以了解分割函数。

class Employee:

    def __init__(self, fullname, age, gender, salary):
        self.fullname = fullname
        self.age = age
        self.gender = gender
        self.salary = salary

    @classmethod
    def func_string_split(cls, employee_str):
        fullname, age, gender, salary = employee_str.split('-')
        return cls(fullname, age, gender, salary)
  
emp_from_csv1 = 'Suresh-27-Male-120000'
emp_from_csv2 = 'John-29-Male-100000'
emp_from_csv3 = 'Tracy-25-Female-155000'
 
emp1 = Employee.func_string_split(emp_from_csv1)
print(emp1.fullname)
print(emp1.gender)
print(emp1.salary)
print(emp1.age)
 
print('----------')
emp3 = Employee.func_string_split(emp_from_csv3)
print(emp3.fullname)
print(emp3.gender)
print(emp3.age)
Suresh
Male
120000
27
----------
Tracy
Female
25

这是另一个关于类方法的示例。这里,我们将日期字符串分割为日、月和年。这里,我们使用了 map 函数 进行分割。

class Date:
 
    def __init__(self, day = 0, month = 0, year = 0):
        self.day = day
        self.month = month
        self.year = year
 
    @classmethod
    def string_to_Date(cls, string_Date):
        day, month, year = map(int, string_Date.split('-'))
        return cls(day, month, year)
 
dt = Date.string_to_Date('31-12-2018')
print(dt.day)
print(dt.month)
print(dt.year)
31
12
2018