静态方法staticmethod和类方法classmethodapp
1、类方法classmethod函数
class Goods: __discount = 0.8 # 静态私有属性 def __init__(self,name,price): self.name = name self.__price = price # price 私有化 @property # 将price方法假装成属性,类外直接调用函数,执行私有属性的一些操做 def price(self): # 不用传参数 return self.__price * Goods.__discount @classmethod # 把一个方法变成类中的方法,这个方法能够在类外直接被类调用,而不须要依托任何对象,即不用实例化也能够 def change_discount(cls,new_discount): # 修改折扣 cls.__discount = new_discount apple = Goods('苹果',5) # 实例化 print(apple.price) Goods.change_discount(0.5) # 这里能够直接用类Goods来调用,不须要依托apple来调用 print(apple.price)
运行结果:spa
4.0 2.5
2、静态方法staticmetho指针
class Login: def __init__(self,name,password): self.name = name self.pwd = password def login(self): pass @staticmethod def get_usr_pwd(): # 这里能够传参数,可是不是特殊的参数,就一些普通的参数 # 本来是和类和对象都无关的函数方法,可是如今是类中的静态方法了 usr = input('用户名: ') pwd = input('密码: ') Login(usr,pwd) Login.get_usr_pwd() # 使用类直接去调用静态方法
3、小结code