如果定义的方法既不想与实例绑定,也不想与类绑定,只是想把类作为它的命名空间,那么可以定义静态方法。
class Account(object):
"""定义银行账户类"""
rate = 0.045
def __init__(self, owner, amount):
self.owner = owner # 定义实例变量
self.amount = amount
# 类方法
@classmethod
def interest_by(cls, amt):
return cls.rate * amt
# 静态方法
@staticmethod
def interest_with(amt):
return Account.interest_by(amt)
interest = Account.interest_by(10_000)
print('利息:{0:.4f}'.format(interest))
interest1 = Account.interest_with(10_000)
print('利息:{0:.4f}'.format(interest1))
使用@staticmethod装饰器,声明方法是静态方法,方法参数指定self和cls。
调用静态方法与调用类方法类似都通过类名实现,但也可以通过实例调用。
类方法和静态方法在很多场景是类似的,只是在定义时有一些区别。类方法需要绑定类,静态方法不需要绑定类,静态方法和类的耦合更加松散。在一个类中定义静态方法只是纬路提供一个基于类名的命名空间。