python静态方法如何定义

722次阅读
没有评论

python静态方法如何定义

1、如何定义python静态方法

python静态方法也可以直接通过类名调用,不需要先创建对象。区别在于类方法的第一个参数是类本身(cls),而静态方法没有这样的参数。如果方法需要与其他类属性或类方法互动,可以定义为类方法;如果方法不需要与其他类属性或类方法互动,可以定义为静态方法。

定义静态方法时,需要在方法的前面加上装饰器 @staticmethod。

class 类:
@staticmethod
    def 静态方法():
        pass

2、python静态方法实例

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)
    
    @staticmethod
    def random_char(string):
        if not isinstance(string, str):
         raise TypeError('需要字符串参数')
        
        return random.choice(string)
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

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