7-1三个装饰器函数

一 property的用法,将一个函数伪装成属性

 1 #第一种写法:
 2 from math import pi
 3 class Circle:
 4     def __init__(self,r):
 5         self.r=r
 6     def mj(self):
 7         return pi*self.r**2
 8     def zc(self):
 9         return 2*pi*self.r
10 c1=Circle(3)
11 print(c1.mj())
12 
13 #第二种写法:用property 将一个函数伪装成为属性
14 class Circle:
15     def __init__(self,r):
16         self.r=r
17     @property
18     def mj(self):
19         return pi*self.r**2
20     @property
21     def zc(self):
22         return 2*pi*self.r
23 c1=Circle(3)
24 print(c1.mj)
25 
26 
27 # property 跟__私有属性的结合 如:苹果打折的问题
28 class Goods():
29     def __init__(self,price,discount):
30         self.__price=price
31         self.discount=discount
32     @property
33     def price(self): #现有的价格
34         return self.__price * self.discount
35     @price.setter #设置一个新的属性即新的价格
36     def price(self,newprice):
37         self.__price=newprice
38     @price.deleter #删除一个价格
39     def price(self):
40         del self.__price
41 
42 apple=Goods(8,0.7)
43 print(apple.price)
44 apple.price=10
45 print(apple.price)
46 print(apple.__dict__)
47 del apple.price
48 print(apple.__dict__)

二 classmethod 


#如果某一个类中的方法 并没有用到这个类的实例中的具体属性
# 只是用到了类中的静态变量 就使用类方法

 1 # classmethod
 2 class Person:
 3     Country='中国人'
 4     @classmethod  #把func变成了一个类方法
 5     def func(cls): #cls指向了类的内存空间
 6         print('当前角色的国家是%s' %cls.Country)
 7 # alex=Person()
 8 # alex.func()
 9 
10 Person.func()

三 staticmethod

#如果某一个类中的方法 并没有用到这个类的实例中的具体属性
# 只是用到了类中的静态变量 就使用类方法

 1 # staticmethod
 2 ## 如果 一个方法 既不会用到对象中的属性也不会用到类中的属性
 3 # 就应该被定义为一个静态方法
 4 
 5 class Student:
 6     @staticmethod #不需要实例化一个学生可以直接调用login登录方法
 7     def login():
 8         name=input('name:')
 9         pwd=input('pwd:')
10         if name =='hu' and pwd =='123':
11             print('登录成功')
12 
13 Student.login()

猜你喜欢

转载自www.cnblogs.com/huningfei/p/9084154.html
7-1