转(静态方法、类方法、属性方法)

一、静态方法

 在类中的方法前面通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法

 1 class Person(object):
 2  
 3     def __init__(self, name):
 4         self.name = name
 5  
 6     @staticmethod
 7     def speak():
 8         print('someone is speaking chinese.')
 9  
10 # 静态方法在类中也不需要传入 self参数

静态方法是不能访问实例变量和类变量的

 1 class Person(object):
 2 
 3  
 4     def __init__(self, name):
 5         self.name = name
 6  
 7     @staticmethod
 8     def speak(self):
 9         print('%s is speaking chinese.' % self.name)
10  
11 p = Person('Bigberg')
12 p.speak()
1 Traceback (most recent call last):
2   File "G:/python/untitled/study6/静态方法.py", line 26, in <module>
3     p.speak()
4 TypeError: speak() missing 1 required positional argument: 'self'
事实上以上代码运行会出错的,说speak 需要一个self参数,但调用时却没有传递,没错,当speak变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了
 
想让以上代码可以正常执行,有两种方法:
1.在调用时将实例本身传给 speak()
 1 class Person(object):
 2  
 3     def __init__(self, name):
 4         self.name = name
 5  
 6     @staticmethod
 7     def speak(self):
 8         print('%s is speaking chinese.' % self.name)
 9  
10 p = Person('Bigberg')
11 p.speak(p)
12  
13 # 输出
14  
15 Bigberg is speaking chinese.

 

2.在方法speak中去掉self,但这也意味着,在speak中不能通过self.调用实例中的其它变量了

 1 class Person(object):
 2  
 3     def __init__(self, name):
 4         self.name = name
 5  
 6     @staticmethod
 7     def speak():                # 方法中已经没有 self 参数了
 8         print('%s is speaking chinese.' % 'anyone')
 9  
10 p = Person('Bigberg')
11 p.speak()
12  
13  
14 #输出
15 anyone is speaking chinese.

 

普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法
 

二、类方法

类方法通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量

        直接访问实例变量会报错,没有该属性

 1 class Person(object):
 2  
 3     def __init__(self, name, country):
 4         self.name = name
 5         self.country = country
 6  
 7     @classmethod
 8     def nationality(self):
 9         print('Bigberg is %s.' % self.country)
10  
11 p = Person('Bigberg', 'CN')
12 p.nationality()
13  
14 # 输出
15 Traceback (most recent call last):
16   File "G:/python/untitled/study6/静态方法.py", line 31, in <module>
17     p.nationality()
18   File "G:/python/untitled/study6/静态方法.py", line 24, in nationality
19     print('Bigberg is %s.' % self.country)
20 AttributeError: type object 'Person' has no attribute 'country'
21  

可以访问类变量,即 全局属性/静态字段 

 1  class Person(object):
 2  
 3     country = 'Chinese'    # 增加一个 全局属性/静态字段
 4  
 5     def __init__(self, name, country):
 6  
 7         self.name = name
 8         self.country = country
 9  
10     @classmethod
11     def nationality(cls):    # 这里将sefl 改为 cls
12         print('Bigberg is %s.' % cls.country)
13  
14 p = Person('Bigberg', 'CN')
15 p.nationality()
16  
17 # 输出
18 Bigberg is Chinese.

三、属性方法 

属性方法的作用就是通过@property把一个方法变成一个静态属性

 

调用属性方法不需要加()号了,直接p.drive就可以了

 1 class Person(object):
 2  
 3     country = 'Chinese'
 4  
 5     def __init__(self, name, country):
 6  
 7         self.name = name
 8         self.country = country
 9  
10     @property
11     def drive(self):
12         print('%s is driving a car.' % self.name)
13 1
14 2
15 p = Person('Bigberg', 'CN')
16 p.drive()
17 1
18 # 输出 <br>Traceback (most recent call last): Bigberg is driving a car. File "G:/python/untitled/study6/静态方法.py", line 38, in <module> p.drive() TypeError: 'NoneType' object is not callable
19 
20 p = Person('Bigberg', 'CN')
21 p.drive
22  
23 # 输出 Bigberg is driving a car.

3.2 setter用法

 1 class Person(object):
 2  
 3     country = 'Chinese'
 4  
 5     def __init__(self, name, country):
 6  
 7         self.name = name
 8         self.country = country
 9         self.car = "LAMBORGHINI"   #当然这里也可以设置为私有属性
10  
11     @property
12     def drive(self):  # 这里不能传参是因为调用的时候,p.drive 没有()了,不能传入
13         print('%s is driving a %s.' % (self.name, self.car))
14  
15     @drive.setter     # 修饰方法drive,可以为属性赋值
16     def drive(self, car):     # 我们要重新定义这个drive方法
17         print("set car:", car)
18         self.car = car
19  
20 p = Person('Bigberg', 'CN')
21 p.drive = 'Tesla'     # 给属性赋值
22 p.drive
23  
24 #输出
25  
26 set car: Tesla
27 Bigberg is driving a Tesla.

3.3 deleter 用法

用del p.drive这种方法来删除属性方法是行不通的:

1 del p.drive
2 
3  
4 #输出
5 Traceback (most recent call last):
6   File "G:/python/untitled/study6/静态方法.py", line 51, in <module>
7     del p.drive
8 AttributeError: can't delete attribute

所以我们就要用到 deleter方法:

 1 class Person(object):
 2  
 3     country = 'Chinese'
 4  
 5     def __init__(self, name, country):
 6  
 7         self.name = name
 8         self.country = country
 9         self.car = "LAMBORGHINI"
10  
11     @property
12     def drive(self):
13         print('%s is driving a %s.' % (self.name, self.car))
14  
15     @drive.setter
16     def drive(self, car):
17         print("set car:", car)
18         self.car = car
19  
20     @drive.deleter   # 修饰 drive 方法,可以删除属性
21     def drive(self):   # 重新定义 drive方法
22         del self.car    #  删除的是属性
23         print("扣了你的车,让你开豪车...")
24  
25 p.drive = 'Tesla'
26 p.drive
27  
28 del p.drive  
29  
30 # 输出
31 set car: Tesla
32 Bigberg is driving a Tesla.
33 扣了你的车,让你开豪车...

四.属性方法应用场景

你想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:

1. 连接航空公司API查询

2. 对查询结果进行解析 

3. 返回结果给你的用户

因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心,用户只要知道结果就行

 1 class Flight(object):
 2  
 3     def __init__(self, name):
 4         self.name = name
 5  
 6     def check_status(self):
 7         print("checking flight %s status" % self.name)
 8         return 1
 9  
10     @property
11     def flight_status(self):
12         status = self.check_status()
13         if status == 0:
14             print("flight got canceled...")
15  
16         elif status == 1:
17             print("flight is arrived...")
18  
19         elif status == 2:
20             print("flight has departured already...")
21  
22         else:
23             print("cannot confirm the flight status")
24  
25     @flight_status.setter
26     def flight_status(self, status):
27         status_dic = {
28             0: "canceled",
29             1: "arrived",
30             2: "departured"
31         }
32         print("\033[31;1mHas changed the flight status to \033[0m", status_dic.get(status))
33  
34     @flight_status.deleter  # 删除
35     def flight_status(self):
36         print("status got removed...")
37  
38 f = Flight('CA980')
39 f.flight_status
40 f.flight_status = 2
41  
42 #输出
43  
44 checking flight CA980 status
45 flight is arrived...
46 Has changed the flight status to  departured

五、总结

 

  1.  静态方法是不可以访问实例变量或类变量的
  2. 类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量
  3. 属性方法将一个方法变为类的属性,调用时不需要加()。有@property 、@属性方法名.setter、@属性方法名.deleter 三种装饰方法
posted @ 2018-05-04 10:13  xajh00789  阅读(313)  评论(0)    收藏  举报