Python中@classmethod、@staticmethod、@property的理解

本文详细解读了Python中classmethod、staticmethod和@property的作用、使用方法及实战示例,包括类方法如何在不创建实例时调用,静态方法如何独立于对象,以及@property如何将方法转换为只读属性以保护数据安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python中@classmethod、@staticmethod、@property的理解

@classmethod

作用:把一个类中的方法指定为类方法,使得它可以在构造函数(初始化函数__init__())前面调用。
使用方法

class sample:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

其中,cls通常用作类方法的第一参数 跟self有点类似( 初始化函数__init__()里面的slef通常用作实例方法的第一参数)。即通常用self来传递当前类的实例–对象,cls传递当前类。self 和cls 没有特别的含义,作用只是把参数绑定到普通的函数上, 不一定非得是self 或cls,可以换成别的xxx。

举例说明

class Data_test(object):
    day=0
    month=0
    year=0
    def __init__(self,year=0,month=0,day=0):
        self.day=day
        self.month=month
        self.year=year
 
    @classmethod
    def get_date(cls,data_as_string):
        #这里第一个参数是cls, 表示调用当前的类名
        year,month,day=map(int,string_date.split('-'))
        date1=cls(year,month,day)
        #返回的是一个初始化后的类
        return date1
 
    def out_date(self):
        print "year :"
        print self.year
        print "month :"
        print self.month
        print "day :"
        print self.day

r=Data_test2.get_date("2016-8-6")
r.out_date()

输出:

year :
2016
month :
8
day :
6

@staticmethod

作用:把一个类中的方法指定为静态方法,使得它可以不创建类实例的情况下调用方法。
使用方法

class sample():
    @staticmethod
    def f(s1,s2):
       ......

举例说明

class Time():
    def __init__(self,sec):
        self.sec = sec
    #声明一个静态方法
    @staticmethod
    def sec_minutes(s1,s2):
        #返回两个时间差
        return abs(s1-s2)
#分别使用类名调用和使用实例调用静态方法
print("----------------------不通过例化的方法调用----------")
print(Time.sec_minutes(10,5)) #类直接调用
t = Time(10) #先实例化类,即对象
print("----------------------通过例化方法调用----------")
print(t.sec_minutes(t.sec,5)) #通过对象进行调用

输出:

----------------------不通过例化的方法调用----------
5
----------------------通过例化方法调用----------
5

@property

作用:类中的装饰器标注,将方法伪装成 属性 的样式使用,即用@property标注的类方法可以类似于属性的方式 实例名.变量名 来调用。@property来创建只读属性,@property装饰器会将方法转换为相同名称的只读属性,可以与所定义的属性配合使用,这样可以防止属性被修改。
使用方法

class sample():
    @property
    def f(s1,s2):
       ......

举例说明

class DataSet(object):
  @property
  def method_with_property(self): ##含有@property
      return 15
  def method_without_property(self): ##不含@property
      return 15
l = DataSet()
print(l.method_with_property) # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。
print(l.method_without_property())  #没有加@property , 必须使用正常的调用方法的形式,即在后面加()

输出:

15
15

防止属性被修改:

class DataSet(object):
    def __init__(self):
        self._images = 1
        self._labels = 2    #定义属性的名称
    @property
    def images(self):   #方法加入@property后,这个方法相当于一个属性,这个属性可以让用户进行使用,而且用户有没办法随意修改。
        return self._images
    # @property
    def labels(self):

        return self._labels


sample = DataSet()
sample.labels = 3
print(sample.labels)
sample.images = 4
print(sample.images)

输出:

3
Traceback (most recent call last):
  File "D:\demo.py", line 23, in <module>
    sample.images = 3
AttributeError: can't set attribute
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值