gpt4 book ai didi

python - 为什么我使用 @classmethod 而不是普通的实例方法

转载 作者:行者123 更新时间:2023-12-01 01:42:38 28 4
gpt4 key购买 nike

我观看了一个 YouTube 视频,解释了 @classmethods、实例方法和 @staticmethods。我了解如何使用它们。我只是不明白何时使用它们以及为什么使用它们。这是他在 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)

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

最佳答案

from_string 而言,它可以用作替代构造函数。它的用法是这样的

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

想一想,如果我想使用这个方法构造我的第一个Employee,如果它是一个实例方法,我该怎么做?我还没有任何实例可以调用它。

<小时/>

set_raise_amt 而言,很明显您正在编辑类(也称为静态)变量,而不是实例变量。话虽如此,使用 getter 和 setter 的 Python 通常被认为是糟糕的。用户应该能够执行以下操作:

Employee.raise_amt = x

关于python - 为什么我使用 @classmethod 而不是普通的实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51710459/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com