为什么要在python中使用类方法? [英] Why should I use a classmethod in python?
问题描述
我正在python中的某个类中编写一个函数,人们建议我向该函数添加 @classmethod
装饰器。
I am writing a function in some class in python, and people suggested to me to add to this function a @classmethod
decorator.
我的代码
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
函数。
I'm almost always using only the _randomize
function.
我的问题是:将类添加到函数中有什么好处?方法
装饰器?
My question is: What is the benefits from adding to a function the classmethod
decorator?
推荐答案
如果看到 _randomize
方法,您没有使用任何实例变量(在init中声明),但使用的是类 var
即 RANDOM_CHOICE ='abcdefg'
。
If you see _randomize
method, you are not using any instance variable (declared in init) in it but it is using a class var
i.e. RANDOM_CHOICE = 'abcdefg'
.
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))
这意味着,您的方法可以不作为实例方法而存在,并且可以在类上直接调用它。
It means, your method can exist without being an instance method and you can call it directly on class.
Randomize._randomize()
现在,问题来了,它有什么优势吗?
Now, the question comes does it have any advantages?
-
我想是的,你不知道
I guess yes, you don't have to go through creating an instance to use this method which will have an overhead.
ran = Randomize() // Extra steps
ran._randomize()
您可以在此处了解更多信息。
You can read more about class and instance variable here.
这篇关于为什么要在python中使用类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!