面向对象【day08】:静态方法、类方法、属性方法(九)

本节内容

  1. 概述
  2. 静态方法
  3. 类方法
  4. 属性方法
  5. 总结

一、概述

  前面我们已经讲解了关于类的很多东西,今天讲讲类的另外的特性:静态方法(staticmethod)、类方法(classmethod)、属性方法(property)

二、静态方法

2.1 定义

说明:在方法名前加上@staticmethod装饰器,表示此方法为静态方法

1
2
3
4
5
6
7
8
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    @staticmethod  #在方法前加上staticmethod 装饰器定义静态方法
    def eat():
        print("dog is eating")

2.2 静态方法特性

特性:只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性

①静态方法,是不可以传入self参数的,但是想传也可以,调用时必须传入实例本身

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    @staticmethod  #定义静态方法
    def eat(self,food):  #可以定义,但是需传入实例本身
        print("{0} is eating {1}".format(self.name,food))
 
= Dog("shabi")
d.eat(d,"hotdog")  #传入实例d本身,否则会报错
 
#输出
shabi is eating hotdog

②静态方法可以用类直接调用,直接调用时,不可以直接传入self,否则会报错

1
2
3
4
5
6
7
8
9
10
11
12
13
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    @staticmethod
    def eat(food):
        print("is eating {0}".format(food))
 
Dog.eat("hotdog")
 
#输出
is eating hotdog

2.3 场景

一般情况下我们需要使用工具包的一些个类的封装,可以用静态方法,比如os模块

1
2
3
4
import os
 
os.system()
os.mkdir()

上面两个方法没有什么必然的联系在里面,所以可以这么用

三、类方法

3.1 定义

说明:在方法名前加上@classmethod装饰器,表示此方法为类方法

1
2
3
4
5
6
7
8
9
class Dog(object):
 
    name = "honggege" #定义静态属性
    def __init__(self,name):
        self.name = name
 
    @classmethod  #定义类方法
    def eat(self,food):
        print("{0} is eating {1}".format(self.name,food))

3.2 类方法特性

特性:只能访问类变量(又叫静态属性),不能访问实例变量

①访问实例变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    @classmethod  #定义类方法
    def eat(self,food):
        print("{0} is eating {1}".format(self.name,food))
 
= Dog("shabihong")
d.eat("hotdog")
 
#输出
  File "D:/PycharmProjects/pyhomework/day7/类方法.py", line 11in <module>
    d.eat("hotdog")
  File "D:/PycharmProjects/pyhomework/day7/类方法.py", line 8in eat
    print("{0} is eating {1}".format(self.name,food))
AttributeError: type object 'Dog' has no attribute 'name'

②访问类变量(又叫静态属性)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Dog(object):
 
    name = "honggege"  #定义类变量
    def __init__(self,name):
        self.name = name
 
    @classmethod
    def eat(self,food):
        print("{0} is eating {1}".format(self.name,food))
 
= Dog("shabihong")
d.eat("hotdog")
 
#输出
honggege is eating hotdog  #调用的是类变量

3.3 使用场景

一个国家,有的国家不允许更改国籍,比如朝鲜,只能去访问写死的变量

四、属性方法

4.1 定义

说明: 在方法名前加上@property装饰器,表示此方法为属性方法

1
2
3
4
5
6
7
8
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    @property  #定义属性方法
    def eat(self):
        print("{0} is eating".format(self.name))

4.2 特性

特性:把一个方法变成一个静态属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    @property   #定义属性方法
    def eat(self):
        print("{0} is eating".format(self.name))
 
= Dog("shabihong")
d.eat #把方法变成静态属性调用
 
#输出
shabihong is eating

我去,按照上面的用法,那我想传入参数咋办呢?

①给转成的静态属性赋值

说明:用@静态方法名.setter去装饰方法,来给转换后的静态属性赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    @property   #定义属性方法
    def eat(self):
        print("{0} is eating {1}".format(self.name,"honggege"))
 
    @eat.setter  #定义一个可以传参的方法
    def eat(self,food):
        print("set to food:",food)
        # self.__food = food
 
= Dog("shabihong")
d.eat = "hotdog"  #给转成的静态变量赋值
d.eat
 
#输出
set to food: hotdog
shabihong is eating honggege

那有些用同学说了,你上面还是没有把food传上去啊,好的,我们现在就来更深入的,请看如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Dog(object):
 
    def __init__(self,name):
        self.name = name
        self.__food = None
 
    @property   #定义属性方法
    def eat(self):
        print("{0} is eating {1}".format(self.name,self.__food))
 
    @eat.setter  #定义可以设置变量赋值
    def eat(self,food):
        print("set to food:",food)
        self.__food = food
 
= Dog("shabihong")
d.eat      #第一份赋值的是None
d.eat = "hotdog"
d.eat    #第二个赋值是hotdog
 
#输出
shabihong is eating None
set to food: hotdog
shabihong is eating hotdog   #说明赋值成功

 ②删除转变的静态属性

说明:用@静态方法名.deleter去装饰,表明可以删除转化后的静态属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Dog(object):
 
    def __init__(self,name):
        self.name = name
        self.__food = None
 
    @property
    def eat(self):
        print("{0} is eating {1}".format(self.name,self.__food))
 
    @eat.setter
    def eat(self,food):
        print("set to food:",food)
        self.__food = food
 
    @eat.deleter   #定义可以删除eat这个静态属性
    def eat(self):
        del self.__food
        print("food 变量删除完毕")
 
= Dog("shabihong")
del d.eat  #删除静态属性eat
 
#输出
food 变量删除完毕

4.3 使用场景

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

1. 连接航空公司API查询

2. 对查询结果进行解析 

3. 返回结果给你的用户

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Flight(object):
    def __init__(self,name):
        self.flight_name = name
 
 
    def checking_status(self):
        print("checking flight %s status " % self.flight_name)
        return  1
 
 
    @property
    def flight_status(self):
        status = self.checking_status()
        if status == 0 :
            print("flight got canceled...")
        elif status == 1 :
            print("flight is arrived...")
        elif status == 2:
            print("flight has departured already...")
        else:
            print("cannot confirm the flight status...,please check later")
     
    @flight_status.setter #修改
    def flight_status(self,status):
        status_dic = {
            0 "canceled",
            1 :"arrived",
            2 "departured"
        }
        print("33[31;1mHas changed the flight status to 33[0m",status_dic.get(status) )
 
    @flight_status.deleter  #删除
    def flight_status(self):
        print("status got removed...")
 
= Flight("CA980")
f.flight_status
f.flight_status =  2 #触发@flight_status.setter
del f.flight_status #触发@flight_status.deleter

五、总结

  1. 静态方法是访问不了类或实例中的任何属性,它已经脱离了类,一般会用在一些工具包中
  2. 类方法,只能访问类变量,不能访问实例变量
  3. 属性方法是把一个方法变成一个静态属性
原文地址:https://www.cnblogs.com/luoahong/p/7208368.html