classmethod、staticclassmethod内置装饰器函数
2024-08-23 12:11:29
# method 英文是方法的意思 # classmethod 类方法
# 当一个类中的方法中只涉及操作类的静态属性时,此时在逻辑上,我们想要直接通过类名就可以调用这个方法去修改类的静态属性,此时可以用这个内置装饰器函数
# staticmethod 静态方法 # 类的方法 classmethod
class Goods:
discount = 0.5 # 折扣
def __init__(self, name, price):
self.name = name
self.__price = price
@property
def price(self):
return self.__price * Goods.discount def change_discount(self, newdiscount): # 修改折扣
Goods.discount = newdiscount apple = Goods('苹果', 5)
print(apple.price) # 2.5
apple.change_discount(2) # 这么操作可以修改折扣,但是概念上无法理解,因为折扣修改的是整个超市的折扣,但这里居然用苹果的方法修改了类的折扣,是不合理的
print(Goods.discount) class Goods:
discount = 0.5 # 折扣
def __init__(self, name, price):
self.name = name
self.__price = price
@property
def price(self):
return self.__price * Goods.discount @classmethod # 被此装饰器修饰的方法,也可以直接被类名调用了 cls代表类,像self(代表对象)
def change_discount(cls, newdiscount): # 修改折扣
cls.discount = newdiscount apple = Goods('苹果', 5)
print(apple.price)
Goods.change_discount(0.2) # 此时就可以直接通过类名去调用方法,从而修改整个类的折扣了
print(apple.price) # 1.0 # 类的静态方法 staticmethod
# 在完全面向对象编程中,如果一个方法既和对象没有关系,又和类没有关系,那么就用staticmethod将这个方法变成一个静态方法
class Login:
def __init__(self, name, password):
self.name = name
self.pwd = password
def login(self):
pass @staticmethod # 被装饰的方法变为静态方法,既和对象没有关系,又和类没有关系,n
def get_usr_pwd():
usr = input('用户名')
pwd = input('密码')
Login(usr, pwd) Login.get_usr_pwd() # 在完全面向对象编程中,如果一个方法既和对象没有关系,又和类没有关系,那么就用staticmethod将这个方法变成一个静态方法,可以直接这样调用 # 类方法和静态方法,都是类调用的
# 对象也是可以调用类方法和静态方法的,但不应该这么用
最新文章
- jQuery的属性
- 用netbeans和xdebug调试php的配置
- android学习笔记 对话框合集
- Game Tutorials
- 移动端混合型App(hybrid app)自动化测试选型与实践
- Android AsyncTask 初探
- 转:php的memcache和memcached扩展区别
- 纯蓝ICON_学习教程
- xmind教程
- Navicat提示Access violation at address 004E9844 in module ‘comctl32.dll’
- mybatis的延迟加载
- thymeleaf时间格式化
- Domain Adaptation (3)论文翻译
- Ajax异步验证登陆或者注册
- 《Python》hashlib模块、configparser模块、logging模块
- Jquery select chosen 插件注意点
- 使用x11vnc作为vncserver端
- webp图片优化
- 使用WebService调用第三方服务
- jplayer.js 与 video.js
热门文章
- (在模仿中精进数据可视化03)OD数据的特殊可视化方式
- spring boot:使mybatis访问多个druid数据源(spring boot 2.3.2)
- go内建方法 new和make区别
- spring boot:给接口增加签名验证(spring boot 2.3.1)
- css和xpath定位补充
- phpstorm 使用xdebug
- 在PostgreSQL中CREATE STATISTICS
- 手撸ORM浅谈ORM框架之Update篇
- JavaScript实现基于对象的队列
- Java反射:new一个宝可梦吧