Understanding @classmethod, @staticmethod, and @property in Python

Understanding @classmethod, @staticmethod, and @property in Python

@classmethod

Function: Designate a method in a class as a class method so that it can be called before the constructor (initialization function __init__()).
How to use:

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

Among them, cls is usually used as the first parameter of the class method, which is similar to self (slef in the initialization function __init__() is usually used as the first parameter of the instance method). That is, self is usually used to pass the instance-object of the current class, and cls is used to pass the current class. self and cls have no special meaning. Their function is just to bind parameters to ordinary functions. It does not have to be self or cls, and can be replaced by other xxx.

for example

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()

Output:

year :
2016
month :
8
day :
6

@staticmethod

Function: Designate a method in a class as a static method, so that it can call the method without creating a class instance.
How to use:

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

for example

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)) #通过对象进行调用

Output:

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

@property

Function: The decorator annotation in the class disguises the method as an attribute. That is, the class method annotated with @property can be used in a manner similar to the attribute instance name.variable name to call. @property to create a read-only property. The @property decorator will convert the method into a read-only property with the same name, which can be used with the defined property to prevent the property from being modified.
How to use:

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

for example

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 , 必须使用正常的调用方法的形式,即在后面加()

Output:

15
15

Prevent properties from being modified:

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)

Output:

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

Guess you like

Origin blog.csdn.net/weixin_46088099/article/details/125956680