python为什么要使用类_为什么要在python中使用类方法?

I am writing a function in some class in python, and people suggested to me to add to this function a @classmethod decorator.

My code:

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))

The suggested change:

@classmethod

def _randomize(cls, random_chars=3):

return ''.join(random.choice(cls.RANDOM_CHOICE)

for _ in range(random_chars))

I'm almost always using only the _randomize function.

My question is: What is the benefits from adding to a function the classmethod decorator?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值