【Python入门自学笔记专辑】——面向对象编程——类方法-静态方法
面向对象编程——类方法-静态方法-装饰器
类方法
“类方法”与“类变量”类似属于类。
定义类方法实例代码如下:
class Account:
"""定义银行账户类"""
interest_rate = 0.0668
def __init__(self, owner, amount):
self.owner = owner # 定义实例变量账户名
self.amount = amount # 定义实例变量账户金额
pass
# 类方法
@classmethod
def interest_by(cls, amt):
return cls.interest_rate * amt
pass
interest = Account.interest_by(12_000.0)
print('计算利息:{0:.4f}'.format(interest))
运行结果
计算利息:801.6000
程序第十二行有一句@classmethod
,意思是声明该方法为类方法
提示:装饰器(Decorators)是Python3.0之后加入的新特性,以@开头修饰函数、方法和类,用来修饰和约数它们,类似于Java中的注解。
静态方法
如果定义的方法既不想与实例绑定,也不想与类绑定,只是想把类作为他的命名空间,那么可以定义静态方法
实例:
class Account:
"""定义银行账户类"""
interest_rate = 0.0668
def __init__(self, owner, amount):
self.owner = owner
self.amount = amount
pass
# 类方法
@classmethod
def interest_by(cls, amt):
return cls.interest_rate * amt
# 静态方法
@staticmethod
def interest_with(amt):
return Account.interest_by(amt)
interest1 = Account.interest_by(12_000.0)
print("计算利息:{0:.4f}".format(interest1))
interest2 - Account.interest_with(12_000.0)
print("计算利息:{0:.4f}".format(interest2))
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 想让你多爱自己一些的开源计时器
· Cursor预测程序员行业倒计时:CTO应做好50%裁员计划
· 大模型 Token 究竟是啥:图解大模型Token
· 用99元买的服务器搭一套CI/CD系统
· 如何在 .NET 中 使用 ANTLR4