博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
classmethod、staticclassmethod内置装饰器函数
阅读量:7209 次
发布时间:2019-06-29

本文共 1633 字,大约阅读时间需要 5 分钟。

# method 英文是方法的意思# classmethod   类方法    # 当一个类中的方法中只涉及操作类的静态属性时,此时在逻辑上,我们想要直接通过类名就可以调用这个方法去修改类的静态属性,此时可以用这个内置装饰器函数# staticmethod  静态方法# 类的方法 classmethodclass 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 = newdiscountapple = Goods('苹果', 5)print(apple.price)  # 2.5apple.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 = newdiscountapple = 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将这个方法变成一个静态方法,可以直接这样调用# 类方法和静态方法,都是类调用的# 对象也是可以调用类方法和静态方法的,但不应该这么用

 

转载于:https://www.cnblogs.com/whylinux/p/9739473.html

你可能感兴趣的文章
JavaScript函数式编程学习
查看>>
ESXi6.7安装流程和bug处理
查看>>
Alibaba Cluster Data 开放下载:270GB 数据揭秘你不知道的阿里巴巴数据中心
查看>>
巧用这19条MySQL优化,效率至少提高3倍
查看>>
【译】Swift算法俱乐部-查找最大/最小值
查看>>
跟着老司机玩转Node自定义命令行
查看>>
react-redux的Provider和connect
查看>>
杂七杂八的前端基础01——函数作用域
查看>>
new操作符具体干了啥
查看>>
iOS响应链
查看>>
『中级篇』docker容器安装wordpress(37)
查看>>
设备节点监听--走在 input 分析之前
查看>>
一行代码实现微光效果
查看>>
React Native学习之 ListView 的简单使用
查看>>
Java 8流操作
查看>>
Load和Initialize往死了问是一种怎样的体验?
查看>>
一致性 Hash 算法的实际应用
查看>>
一个文科妹子走上前端开发不归路(干货分享)
查看>>
中国行政区划信息JS库china-location
查看>>
Vert.x 发送邮件
查看>>