您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页python静态方法如何定义

python静态方法如何定义

来源:二三娱乐

定义

1、静态方法也可以直接通过类名调用,不需要先创建对象。区别在于类方法的第一个参数是类本身(cls),而静态方法没有这样的参数。

如果方法需要与其他类属性或类方法互动,可以定义为类方法;如果方法不需要与其他类属性或类方法互动,可以定义为静态方法。

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

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

实例

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)

以上就是python静态方法的定义,希望对大家有所帮助。更多Python学习指路:

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务