python静态方法如何定义

Python (244) 2023-07-26 22:35:54

定义

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

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

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

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

实例

importrandom

classChar:
letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits='0123456789'
@classmethod
defrandom_letter(cls):
returnrandom.choice(cls.letters)
@classmethod
defrandom_digits(cls):
returnrandom.choice(cls.digits)

@staticmethod
defrandom_char(string):
ifnotisinstance(string,str):
raiseTypeError('需要字符串参数')

returnrandom.choice(string)

以上就是python静态方法的定义,希望对大家有所帮助。

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

THE END

发表回复