python类方法如何定义

325次阅读
没有评论

python类方法如何定义

1、定义

类方法的定义需要借助于装饰器。

在定义类方法时,需要在方法前面添加装饰@classmethod。

class 类:

@classmethod
    def 类方法(cls):
        pass

2、注意

不同于对象方法。类方法的第一个参数通常被命名为cls,表示当前类本身。我们可以通过这个参数引用类属性或其他类方法。

这种类型的属性可以在类别方法中使用,但不能使用这种类型的对象属性。由于类方法属于类别,而对象属性属于对象,因此在使用类方法时可能没有对象被创建。

3、实例

import random
 
class Char:
    letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    digits = '0123456789'
    @classmethod
    def random_letter(cls):
        return random.choice(cls.letters)
    @classmethod
    def random_digits(cls):
        return random.choice(cls.digits)
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-04-24发表,共计515字。
新手QQ群:570568346,欢迎进群讨论 Python51学习