内置装饰器一:@classmethod、@staticmathod

使用 @classmethod 和 @staticmathod 后,类的方法的调用

  • 一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。
  • 而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。
    这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。

@staticmethod 和 @classmethod 都可以直接类名.方法名()来调用,他们的区别

  • @staticmethod 不需要表示自身对象的 self 和自身类的 cls 参数,就跟使用函数一样。
  • @classmethod 也不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数。
  • 如果在 @staticmethod 中要调用到这个类的一些属性方法,只能直接类名.属性名或类名.方法名。
  • 而 @classmethod 因为持有 cls 参数,可以来调用类的属性,类的方法,实例化对象等,避免硬编码。

总结:
简单使用的时候使用@staticmethod, 需要调用类的其他属性时使用@classmethod

示例

# -*- coding: utf-8 -*-

class Washer:
    company = "Li"
    def __init__(self,water=10,scour=2):
        self._water = water
        self.scour = scour
        self.year = 2010

    @staticmethod
    def spins_ml(spins):
        # print("company:",Washer.company)
        # print('year:',self.year)
        return spins * 0.4

    @classmethod
    def get_washer(cls,water,scour):
        print("company:",Washer.company)
        print('year:',self.year)
        return cls(water,cls.spins_ml(scour))

    @property
    def water(self):
        return self._water

    @water.setter
    def water(self,water):
        if 0 < water <=500:
            self._water = water
        else:
            print("set Failure!")

    @property
    def total_year(self):
        return 2015 - self.year

    def set_water(self,water):
        self.water = water

    def set_scour(self,scour):
        self.scour = scour

    def add_water(self):
        print('Add water:',self.water)

    def add_scour(self):
        print('Add scour:',self.scour)

    def start_wash(self):
        self.add_water()
        self.add_scour()
        print('Start wash...')

参考资料:http://blog.willdx.me/web/面向对象进阶.html

原文地址:https://www.cnblogs.com/ronky/p/9884155.html