静态方法与类方法类似,只是它们没有任何额外的参数。

它们用 staticmethod 装饰器标记。

例如:

class Pizza:
  def __init__(self, toppings):
    self.toppings = toppings
    print(self.toppings)

  @staticmethod
  def validate_topping(topping):
    if topping == "pineapple":
      raise ValueError("No pineapples!")
    else:
      return True

ingredients = ["cheese", "onions", "spam"]
if all(Pizza.validate_topping(i) for i in ingredients):
  pizza = Pizza(ingredients) 
======
结果:
['cheese', 'onions', 'spam']

all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False
当程序出错时,python会自动触发异常,也可以通过raise显示引发异常
一旦执行了raise语句,raise之后的语句不在执行
如果加入了try,except,那么except里的语句会被执行
除了可以从类的一个实例调用它们之外,静态方法的行为与纯函数类似。

最后修改:2022 年 12 月 05 日
如果觉得我的文章对你有用,请随意赞赏