本节内容

  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("\033[31;1mHas changed the flight status to \033[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. 属性方法是把一个方法变成一个静态属性

面向对象【day08】:静态方法、类方法、属性方法(九)的更多相关文章

  1. python静态方法类方法属性方法

    Python的静态方法和类成员方法都可以被类或实例访问,两者概念不容易理清,但还是有区别的: 1)静态方法无需传入self参数,类成员方法需传入代表本类的cls参数: 2)从第1条,静态方法是无法访问 ...

  2. python面向对象(七)属性方法的添加

    ​ 通常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性.下来我就讲下添加属性和方法,同时也将下限值添加属性方法. 添加属性 ...

  3. Python面向对象静态方法,类方法,属性方法

    Python面向对象静态方法,类方法,属性方法 属性: 公有属性 (属于类,每个类一份) 普通属性 (属于对象,每个对象一份) 私有属性 (属于对象,跟普通属性相似,只是不能通过对象直接访问) 方法: ...

  4. python 面向对象静态方法、类方法、属性方法、类的特殊成员方法

    静态方法:只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性. 在类中方法定义前添加@staticmethod,该方法就与类中的其他(属性,方法)没有关系,不能通过实例化类调用方法使用 ...

  5. Python的程序结构[1] -> 方法/Method[1] -> 静态方法、类方法和属性方法

    静态方法.类方法和属性方法 在 Python 中有三种常用的方法装饰器,可以使普通的类实例方法变成带有特殊功能的方法,分别是静态方法.类方法和属性方法. 静态方法 / Static Method 在 ...

  6. Python笔记_第四篇_高阶编程_实例化方法、静态方法、类方法和属性方法概念的解析。

    1.先叙述静态方法: 我们知道Python调用类的方法的时候都要进行一个实例化的处理.在面向对象中,一把存在静态类,静态方法,动态类.动态方法等乱七八糟的这么一些叫法.其实这些东西看起来抽象,但是很好 ...

  7. Python面向对象05 /私有成员、类方法、静态方法、属性、isinstance/issubclass

    Python面向对象05 /私有成员.类方法.静态方法.属性.isinstance/issubclass 目录 Python面向对象05 /私有成员.类方法.静态方法.属性.isinstance/is ...

  8. python 面向对象专题(五):私有成员、类方法、静态方法、属性、isinstance/issubclass

    https://www.cnblogs.com/liubing8/p/11325421.html 目录 Python面向对象05 /私有成员.类方法.静态方法.属性.isinstance/issubc ...

  9. python7 静态方法、类方法、属性方法 ;反射;异常处理

      #-*- coding:utf8 -*- # 静态方法@staticmethod # 静态方法(当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了.) clas ...

随机推荐

  1. 实验1--用C语言编程四则运算

    #include<stdio.h>#include<stdlib.h>#include <time.h>#define N 30main(){int a,b,k,i ...

  2. SpringMvc常见问题汇总

    1.Service类未用@Service注解2016-10-26 17:31:36 [org.springframework.web.context.ContextLoader]-[ERROR] Co ...

  3. Java与JavaScript 完美实现字符串拆分(利用数组存储)与合并的互逆操作

    Java: String typeStr = "1,2"; String[] typeArray = typeStr.split(","); typeStr = ...

  4. 批处理-For详解

    大纲 一 前言 二 for语句的基本用法 三 for /f (delims.tokens.skip.eol.userbackq.变量延迟) 四 for /r (递归遍历) 五 for /d (遍历目录 ...

  5. Spring AOP切点表达式用法总结

    1. 简介        面向对象编程,也称为OOP(即Object Oriented Programming)最大的优点在于能够将业务模块进行封装,从而达到功能复用的目的.通过面向对象编程,不同的模 ...

  6. jquery Ajax get()/post()

    get()/post()是通過http get/post向服務器請求數據的. http get vs post: get:向指定資源獲取數據 post項指定資源提交數據. get是向遠程服務器的獲取數 ...

  7. js數字

    js數字只有一種類型:不是類型語言. js的數字可以使用科學計數法或者不使用科學計數法: js都是64位的, 如果是整數,(不使用科學計數法或者是小數點)最大15位的: 如果是浮點數,最大17位的,浮 ...

  8. linux下拷贝文件夹的时候排除其中的一些目录

    http://blog.csdn.net/wind19/article/details/8960574 使用find cd /usr find ./tmp/ | grep -v tmp/dirc | ...

  9. windows下 navicat_premium破解方法

    https://blog.csdn.net/qq_21205435/article/details/78902052

  10. List泛型集合

    List和数组 相同点: 都可以控制元素类型 不同点: List的长度是可变的,所以list比数组更容易掌控 List属性 1.Count 获取集合中实际包含的元素个数 2.Capcity 集合中可以 ...