python classmethod使用 python中的class_static的@classmethod的巧妙用法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python classmethod使用 python中的class_static的@classmethod的巧妙用法

peterpan--1998   2021-06-21 我要评论
想了解python中的class_static的@classmethod的巧妙用法的相关内容吗,peterpan--1998在本文为您仔细讲解python classmethod使用的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python,classmethod使用,python,class_static,下面大家一起来学习吧。

python中的class_static的@classmethod的使用 classmethod的使用,主要针对的是类而不是对象,在定义类的时候往往会定义一些静态的私有属性,但是在使用类的时候可能会对类的私有属性进行修改,但是在没有使用class method之前对于类的属性的修改只能通过对象来进行修改,这是就会出现一个问题当有很多对象都使用这个属性的时候我们要一个一个去修改对象吗?答案是不会出现这么无脑的程序,这就产生classmethod的妙用。请看下面的代码:

class Goods:
    __discount = 0.8
    def __init__(self,name,money):
        self.__name = name
        self.__money = money
    @property
    def price(self):
        return self.__money*Goods.__discount
    @classmethod
    def change(cls,new_discount):#注意这里不在是self了,而是cls进行替换
        cls.__discount = new_discount

apple = Goods('苹果',5)
print(apple.price)
Goods.change(0.5) #这里就不是使用apple.change()进行修改了
print(apple.price)

上面只是简单的列举了class method的一种使用场景,后续如果有新的会持续更新本篇文章 2.既然@staticmethod和@classmethod都可以直接类名.方法名()来调用,那他们有什么区别呢

从它们的使用上来看,
@staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。

如果在@staticmethod中要调用到这个类的一些属性方法,只能直接类名.属性名或类名.方法名。
而@classmethod因为持有cls参数,可以来调用类的属性,类的方法,实例化对象等,避免硬编码。
下面上代码。

class A(object):  
    bar = 1  
    def foo(self):  
        print 'foo'  

    @staticmethod  
    def static_foo():  
        print 'static_foo'  
        print A.bar  

    @classmethod  
    def class_foo(cls):  
        print 'class_foo'  
        print cls.bar  
        cls().foo()  
###执行  
A.static_foo()  
A.class_foo() 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们