Python类总结-ClassMethod, StaticMethod

classmethod-把classmethod装饰的方法变成为类中的方法

  • 作用: 把classmethod装饰的方法变成为类中的方法,这个方法直接可以被类调用,不需要依托任何对象
  • 应用场景: 当这个方法只涉及静态属性的时候,就应该使用classmethod装饰这个方法

#类里面的操作行为
class Goods:
    __discount = 0.5
    def __init__(self,name, price):
        self.name = name
        self.__price = price #折扣前价格定义为私有的

    @property
    def price(self): #折扣后的价格定义为一个方法并用property装饰,进行一些操作
        return self.__price*Goods.__discount
    @classmethod #把classmethod装饰的方法变成为类中的方法,这个方法直接可以被类调用,不需要依托任何对象
    def change_discount(cls,new_discount): #cls是固定参数,指代的是该类
        cls.__discount  = new_discount
#当这个方法只涉及静态属性的时候,就应该使用classmethod装饰这个方法
apple = Goods('苹果', 5)
print(apple.price)
Goods.change_discount(0.8)
print(apple.price)

StaticMethod- 把和类或对象无关的方法放入某个类 (借鉴JAVA的一切皆对象的原则)

class Login:
    def __init__(self,name, password):
        self.name = name
        self.password = password
    def login(self):
        pass
    @staticmethod #装饰一个和类无关的方法
    def get_usr_pwd(): #无需传任何参数,self也不要
        usr = input('username:')
        password = input('password:')
        Login(usr,password)
Login.get_usr_pwd() #可以直接调用Login类中get_usr_pwd,且调用之前无需实例化对象

总结

  • 类方法和静态方法都是类调用的
  • 对象可以调用类的静态方法和类方法
  • 类方法有个默认参数cls,代表类
  • 静态方法没有默认的参数
原文地址:https://www.cnblogs.com/konglinqingfeng/p/9674185.html