静态方法、类方法、属性方法

一、静态方法

1.1、定义

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

class Person(object):

    def __init__(self, name):
        self.name = name

    @staticmethod
    def speak():
        print(‘someone is speaking chinese.‘)

# 静态方法在类中也不需要传入 self参数

  

1.2、静态方法的特性

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

class Person(object):

    def __init__(self, name):
        self.name = name

    @staticmethod
    def speak(self):
        print(‘%s is speaking chinese.‘ % self.name)

p = Person(‘Bigberg‘)
p.speak()

# 我们在 speak(self) 函数中传入 self

  事实上以上代码运行会出错的,说speak 需要一个self参数,但调用时却没有传递,没错,当speak变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。  

Traceback (most recent call last):
  File "G:/python/untitled/study6/静态方法.py", line 26, in <module>
    p.speak()
TypeError: speak() missing 1 required positional argument: ‘self‘

  想让以上代码可以正常执行,有两种方法:

  1. 在调用时将实例本身传给 speak() 
class Person(object):

    def __init__(self, name):
        self.name = name

    @staticmethod
    def speak(self):
        print(‘%s is speaking chinese.‘ % self.name)

p = Person(‘Bigberg‘)
p.speak(p)

# 输出

Bigberg is speaking chinese.

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

class Person(object):

    def __init__(self, name):
        self.name = name

    @staticmethod
    def speak():                # 方法中已经没有 self 参数了
        print(‘%s is speaking chinese.‘ % ‘anyone‘)

p = Person(‘Bigberg‘)
p.speak()

#输出
anyone is speaking chinese.

  

1.3 总结

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

二、类方法

  2.1、定义

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

  2.2、访问实例变量

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

class Person(object):

    def __init__(self, name, country):
        self.name = name
        self.country = country

    @classmethod
    def nationality(self):
        print(‘Bigberg is %s.‘ % self.country)

p = Person(‘Bigberg‘, ‘CN‘)
p.nationality()

# 输出
Traceback (most recent call last):
  File "G:/python/untitled/study6/静态方法.py", line 31, in <module>
    p.nationality()
  File "G:/python/untitled/study6/静态方法.py", line 24, in nationality
    print(‘Bigberg is %s.‘ % self.country)
AttributeError: type object ‘Person‘ has no attribute ‘country‘

# 提示没有一个 country 属性  

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

class Person(object):

    country = ‘Chinese‘    # 增加一个 全局属性/静态字段

    def __init__(self, name, country):

        self.name = name
        self.country = country

    @classmethod
    def nationality(cls):    # 这里将sefl 改为 cls, 其实self也能运行
        print(‘Bigberg is %s.‘ % cls.country)

p = Person(‘Bigberg‘, ‘CN‘)
p.nationality()

# 输出
Bigberg is Chinese.

三、属性方法 

  3.1、定义

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

class Person(object):

    country = ‘Chinese‘

    def __init__(self, name, country):

        self.name = name
        self.country = country

    @property
    def drive(self):
        print(‘%s is driving a car.‘ % self.name)
p = Person(‘Bigberg‘, ‘CN‘)
p.drive()
# 输出 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

  调用会出错误, 说NoneType is not callable, 因为eat此时已经变成一个静态属性了, 不是方法了, 想调用已经不需要加()号了,直接p.drive就可以了

  正常调用: 

p = Person(‘Bigberg‘, ‘CN‘)
p.drive

# 输出

Bigberg is driving a car.

  

  3.2 setter用法

  如果我们想在属性方法里传参,比如车的品牌,我们就要用setter了,具体用法  @属性方法名.setter 

class Person(object):

    country = ‘Chinese‘

    def __init__(self, name, country):

        self.name = name
        self.country = country
        self.car = "LAMBORGHINI"   # 定义车品牌为兰博基尼

    @property
    def drive(self):
        print(‘%s is driving a %s.‘ % (self.name, self.car))

p = Person(‘Bigberg‘, ‘CN‘)
p.drive

# 输出
Bigberg is driving a LAMBORGHINI.

  很显然我们开出去的车就是兰博基尼,如果我们想自己传入车品牌呢?比如 特斯拉: 

class Person(object):

    country = ‘Chinese‘

    def __init__(self, name, country):

        self.name = name
        self.country = country
        self.car = "LAMBORGHINI"   #当然这里也可以设置为私有属性

    @property
    def drive(self):  # 这里不能传参是因为调用的时候,p.drive 没有()了,不能传入
        print(‘%s is driving a %s.‘ % (self.name, self.car))

    @drive.setter     # 修饰方法drive,可以为属性赋值
    def drive(self, car):     # 我们要重新定义这个drive方法
        print("set car:", car)
        self.car = car

p = Person(‘Bigberg‘, ‘CN‘)
p.drive = ‘Tesla‘     # 给属性赋值
p.drive

#输出

set car: Tesla
Bigberg is driving a Tesla.

  3.3 deleter 用法

  用来删除属性方法,具体用法 @属性方法名.deleter  

# 以上例
# 我们可以发现普通属性是可以通过del直接删除的
# 比如
print(p.name)
del p.name
print(p.name)

# 输出

Traceback (most recent call last):
Bigberg
  File "G:/python/untitled/study6/静态方法.py", line 49, in <module>
    print(p.name)
AttributeError: ‘Person‘ object has no attribute ‘name‘

#删除之后就不能再调用了

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

del p.drive

#输出
Traceback (most recent call last):
  File "G:/python/untitled/study6/静态方法.py", line 51, in <module>
    del p.drive
AttributeError: can‘t delete attribute

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

class Person(object):

    country = ‘Chinese‘

    def __init__(self, name, country):

        self.name = name
        self.country = country
        self.car = "LAMBORGHINI"

    @property
    def drive(self):
        print(‘%s is driving a %s.‘ % (self.name, self.car))

    @drive.setter
    def drive(self, car):
        print("set car:", car)
        self.car = car

    @drive.deleter   # 修饰 drive 方法,可以删除属性
    def drive(self):   # 重新定义 drive方法
        del self.car    #  删除的是属性
        print("扣了你的车,让你开豪车...")

p.drive = ‘Tesla‘
p.drive

del p.drive   

# 输出
set car: Tesla
Bigberg is driving a Tesla.
扣了你的车,让你开豪车...

  让我们在秋名山再开一次车...

p.drive

# 输出
扣了你的车,让你开豪车...
Traceback (most recent call last):
  File "G:/python/untitled/study6/静态方法.py", line 57, in <module>
    p.drive
  File "G:/python/untitled/study6/静态方法.py", line 28, in drive
    print(‘%s is driving a %s.‘ % (self.name, self.car))
AttributeError: ‘Person‘ object has no attribute ‘car‘

# 提示没有这个属性了

四、属性方法应用场景

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

1. 连接航空公司API查询

2. 对查询结果进行解析

3. 返回结果给你的用户

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

class Flight(object):

    def __init__(self, name):
        self.name = name

    def check_status(self):
        print("checking flight %s status" % self.name)
        return 1

    @property
    def flight_status(self):
        status = self.check_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")

    @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...")

f = Flight(‘CA980‘)
f.flight_status
f.flight_status = 2

#输出

checking flight CA980 status
flight is arrived...
Has changed the flight status to  departured

  

五、总结

  1. 静态方法是不可以访问实例变量或类变量的
  2. 类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量
  3. 属性方法将一个方法变为类的属性,调用时不需要加()。有@property 、@属性方法名.setter、@属性方法名.deleter 三种装饰方法
时间: 2024-08-10 23:27:00

静态方法、类方法、属性方法的相关文章

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

Python的静态方法和类成员方法都可以被类或实例访问,两者概念不容易理清,但还是有区别的: 1)静态方法无需传入self参数,类成员方法需传入代表本类的cls参数: 2)从第1条,静态方法是无法访问实例变量的,而类成员方法也同样无法访问实例变量,但可以访问类变量: 3)静态方法有点像函数工具库的作用,而类成员方法则更接近类似Java面向对象概念中的静态方法. 静态方法 @staticmethod    def staticmd():        print '静态方法 @classmetho

类的各种自带方法,静态方法,属性方法,类方法等

#coding=utf-8 class Dog(object): ''' 类的描述 ''' def __init__(self,name): self.name = name self.__food = None @staticmethod #实际上跟类没什么关系,单纯的函数,但是必须通过类名来调用 def eat(food): print ('%s is eating %s'%('xiaohuang',food)) @classmethod #类方法,只能访问类变量,不能访问实例变量 def

day7 静太方法 类方法 属性方法 反射 导常

类方法 1 '''是类对象所拥有的方法,需要用修饰器@classmethod来标识其为类方法,对于类方法 2 ,第一个参数必须是类对象,一般以cls作为第一个参数(当然可以用其他名称的变量作为其第一个参数, 3 但是大部分人都习惯以'cls'作为第一个参数的名字,就最好用'cls'了),能够通过实例对象和类对象去访问.''' 4 5 lass People(object): 6 country = 'china' 7 8 #类方法,用classmethod来进行修饰 9 @classmethod

静态方法@staticmethod 属性方法@property

多态 接口重用, 一种接口,多种实现 静态方法@staticmethod 只是名义上归类管理, 实际上在静态方法里访问不了类或实例中的任何属性类方法@classmethod 只能访问类变量,不能访问实例变量 属性方法@property 把一个方法变成一个静态属性给参数赋值要重新定义一个同名函数,并且前面加@属性名.setter import os# os.system()# os.mkdir() class Dog(object): def __init__(self,name): self.n

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

本节内容 概述 静态方法 类方法 属性方法 总结 一.概述 前面我们已经讲解了关于类的很多东西,今天讲讲类的另外的特性:静态方法(staticmethod).类方法(classmethod).属性方法(property) 二.静态方法 2.1 定义 说明:在方法名前加上@staticmethod装饰器,表示此方法为静态方法 1 2 3 4 5 6 7 8 class Dog(object):     def __init__(self,name):         self.name = nam

python学习笔记之面向对象中的静态方法、类方法、属性方法总结

静态方法 类方法 属性方法 一.静态方法 可以利用@staticmethod装饰器把一个方法变成一个静态方法.静态方法不可以方法实例变量或者类变量,也就是说不可以使用self.属性这样子调用实例属性了.其实静态方法就和类本身没什么关系了,它和类 唯一的关联就是需要通过类名来调用这个方法. 错误调用方式: class Dog(object): def __init__(self,name): self.name = name @staticmethod #把eat方法变为静态方法 def eat(

python第三十三天----静态方法、类方法、属性方法

@staticmethod 装饰后,类中的方法转成静态方法 1 class a: 2 3 @staticmethod 4 def b(self): 5 print('') 静态方法不可以访问实例变量或类变量,相当于类中的工具包.如os,  system 等 import的模块一般 @classmethod装饰后,类中的方法转成类方法,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量 1 class b(object): 2 name='aa' 3 @classmethod 4

Python之路 - 属性方法,类方法,静态方法

本章内容 属性方法 类方法 静态方法 属性方法 属性方法就是通过使用装饰器 @property , 将一个方法变成一个静态属性 , 于是我们就可以通过访问属性 , 来或得一个方法的返回值 1 from urllib.request import urlopen 2 class Web_page: 3 def __init__(self, url): 4 self.url = url 5 self.__content = None 6 # 将content方法变成属性 7 @property 8

静态方法,类方法,属性方法

1.静态方法:只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性.相当于类的工具包. class Dog(object): def __init__(self,name): self.name=name @staticmethod #实际上跟类没什么关系了,相当于一个独立的函数. def eat(self,food): print("%s is eating %s"%(self.name,food)) def drink(self,food): print("