Python全系列 教程
3567个小节阅读:5931.2k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
我们在面向对象学习时,学习过三种装饰器: property
、 staticmethod
、 classmethod
。
property装饰器
property
装饰器用于类中的函数,使得我们可以像访问属性一样来获取一个函数的返回值。
【示例】prperty装饰器的使用
xxxxxxxxxx
class User:
def __init__(self,name,month_salary):
self.name = name
self.month_salary = month_salary
@property
def year_salary(self):
return int(self.month_salary)*12
if __name__ == '__main__':
u1 = User("gaoqi","30000")
print(u1.year_salary)
staticmethod装饰器
staticmethod
装饰器同样是用于类中的方法,这表示这个方法将会是一个静态方法,意味着该方法可以直接被调用无需实例化,但同样意味着它没有 self
参数,也无法访问实例化后的对象。
【示例】staticmethod装饰器的使用
xxxxxxxxxx
class Person:
@staticmethod
def say_hello():
print("hello world!")
if __name__ == '__main__':
Person.say_hello()
classmethod装饰器
classmethod
这个方法是一个类方法。该方法无需实例化,没有 self
参数。相对于 staticmethod
的区别在于它会接收一个指向类本身的 cls
参数。
【示例】classmethod装饰器
xxxxxxxxxx
class Person:
@classmethod
def say_hello(cls):
print(f"我是{cls.__name__}")
print("hello world!")
if __name__ == '__main__':
Person.say_hello()