1
我正在写一些Python中的函数,人们建议我添加一个@classmethod
装饰器。为什么要在python中使用classmethod?
我的代码:
import random
class Randomize:
RANDOM_CHOICE = 'abcdefg'
def __init__(self, chars_num):
self.chars_num = chars_num
def _randomize(self, random_chars=3):
return ''.join(random.choice(self.RANDOM_CHOICE)
for _ in range(random_chars))
建议的更改:
@classmethod
def _randomize(cls, random_chars=3):
return ''.join(random.choice(cls.RANDOM_CHOICE)
for _ in range(random_chars))
我几乎总是只使用_randomize
功能。
我的问题是:添加到一个函数classmethod
修饰器有什么好处?
它更清楚地表明该方法不使用实例中的任何状态,通常命名为“self”。此外,它意味着您可以在课堂上测试它,而无需创建实例。 – jonrsharpe
另外,如果这个类不包含其他内容,那么最好使用一个函数和'functools.partial()'。也许。 –