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

在类中的方法加如下装饰器

属性方法:@property将方法变为类的一个静态属性,调用的时候无需加括号。对外隐藏实现细节,对于用户来讲,感觉就是在查一个写死的东西

class Flight(object):
    def __init__(self,name):
        self.name = name
    def check_flight(self):
        print('checking flight %s: status'% self.name)
        status = 3
        return status
    @property #为类的一个静态属性,调用的时候无需加括号。对外隐藏实现细节,对于用户来讲,感觉就是在查一个写死的静态属性
    def flight_status(self):
        status  = self.check_flight()
        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_dict = {
            0:'canceled',
            1:'arrived',
            2:'departured'
        }
        print('\033[31;1mhas changed flight:%s status to:%s\033[0m'%(self.name,status_dict[status]))
    @flight_status.deleter #加上删除装饰器,这个静态方法就可以被删除
    def flight_status(self):
        print('status Func got removed')
f1 = Flight("川航3U8633")
f1.flight_status  #不用加括号
f1.flight_status = 1
f1.flight_status
del f1.flight_status
f1.flight_status
View Code

静态方法:@staticmethod

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

class Dog(object):

    def __init__(self,name):
        self.name = name
    def talk(self):
        print('%s talking: 旺旺旺!'% self.name)
    @staticmethod
    def eat(self,food):
        print('%s eating %s'%(self.name,food))

d1 = Dog('ChenRonghua')
d1.eat('包子')
View Code
Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/Python3_study/day6/静态方法_类方法.py", line 15, in <module>
    d1.eat('包子')
TypeError: eat() missing 1 required positional argument: 'food'

类方法:@classmethod

只能访问类变量,不能访问实例变量

class Dog(object):
    name = '类方法调用测试用类变量'
    def __init__(self,name):
        self.name = name
    def talk(self):
        print('%s talking: 旺旺旺!'% self.name)
    # @staticmethod
    @classmethod
    def eat(self,food):
        print('%s eating %s'%(self.name,food))
d1 = Dog('ChenRonghua')
d1.eat('包子')
View Code
类方法调用测试用类变量 eating 包子

Process finished with exit code 0

  

猜你喜欢

转载自www.cnblogs.com/zhangmingda/p/9162425.html