为什么我使用@classmethod而不是普通的实例方法[重复]

问题描述 投票:0回答:1

我观看了一个解释@classmethods,实例方法和@staticmethods的youtube视频。我理解如何使用它们。我只是不明白什么时候使用它们为什么。这是他为youtube视频中的@classmethods提供的代码。

class Employee:

    # class object attributes
    num_of_emps = 0
    raise_amt = 1.04

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.email = first + '.' + last + '@email.com'
        self.pay = pay

        Employee.num_of_emps += 1

    def fullname(self):
        return f'{self.first} {self.last}'

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    @classmethod
    def set_raise_amt(cls, amount):
        cls.raise_amt = amount

    @classmethod
    def from_string(cls, emp_str):
        first, last, pay = emp_str.split('-')
        return cls(first, last, pay)


emp_1 = Employee('Corey', 'Shaffer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)

emp_3 = Employee.from_string('Ezekiel-Wootton-60000')
print(emp_3.email)
print(emp_3.pay)

为什么我使用@classmethod作为from_string方法?我认为使用没有装饰器的普通实例方法更有意义,因为我们不是指类。对?!?我们指的是将字符串作为参数传递的每个实例。

python class-method
1个回答
1
投票

from_string的情况下,它可以用作替代构造函数。它的用法就是这样

new_employee = Employee.from_string('Corey-Shaffner-50000')

想想看,如果我想使用这种方法构建我的第一个Employee,如果它是一个实例方法我该怎么做?我还没有任何实例可以打电话给它。


set_raise_amt的情况下,很明显你正在编辑一个类(又名静态)变量,而不是一个实例变量。话虽这么说,使用getter和setter通常被认为是糟糕的python。用户应该能够做到:

Employee.raise_amt = x
© www.soinside.com 2019 - 2024. All rights reserved.