zoukankan      html  css  js  c++  java
  • @property @classmethod @staticmethod

    
    
    
    
    Python内置的  @property装饰器就是负责把一个方法变成属性调用的
    from math import pi
    # class Circle(): # def __init__(self,r,name): # self.r = r # self.name = name # @property # def chang(self): # # return 2*pi*self.r # @property # def area(self): # return self.r**2*pi # c1 = Circle(3,"小张") # # print(c1.r) # print(c1.name) # print(c1.chang) # print(c1.area) # class Goods: # __discount = 0.8 # num=200 # def __init__(self,name,price): # self.name = name # self.__price = price # @property #把一个方法变成属性调用 # def price(self): # return self.__price * Goods.__discount # @classmethod # 把一个方法 变成一个类中的方法,这个方法就直接可以被类调用,不需要依托任何对象 # def change_discount(cls,new_discount): # 修改折扣 类方法默认有一个参数cls代表这个类 # cls.__discount = new_discount # cls.num = 100000 # apple = Goods('苹果',5) # print(apple.price) # Goods.change_discount(0.5) # 类调用 # print(apple.price) # apple.change_discount(10) #对象调用 # print(apple.price) # print(Goods.num) # print(apple.num) # 当这个方法的操作只涉及静态属性的时候 就应该使用staticmethod来装饰这个方法 # 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()#不需要实例化对象,直接类名调用方法 # 在完全面向对象的程序中, # 如果一个函数 既和对象没有关系 也和类没有关系 那么就用staticmethod将这个函数变成一个静态方法 # # 类方法和静态方法 都是类调用的 # 对象可以调用类方法和静态方法么? 可以 一般情况下 推荐用类名调用 # 类方法 有一个默认参数 cls 代表这个类 cls # 静态方法 没有默认的参数 就象函数一样
    
    
    
     
  • 相关阅读:
    记一次x87 FPU寄存器栈溢出
    从Unit Bezier的实现学习两种经典数值求解算法
    OI Memory 后记(1):IOI2021 漫谈
    Solution -「BZOJ #3786」星系探索
    Solution -「UOJ #46」玄学
    Solution -「多校联训」神
    Solution -「多校联训」自动机
    Solution -「多校联训」取石子游戏
    Solution -「HDU 6875」Yajilin
    Solution -「多校联训」最小点覆盖
  • 原文地址:https://www.cnblogs.com/chvv/p/9956150.html
Copyright © 2011-2022 走看看