1. 程式人生 > >python學習筆記8--面向對象--屬性和方法詳解

python學習筆記8--面向對象--屬性和方法詳解

confirm 報錯 方式 系列 dep 是個 應用 all icm

屬性:

  公有屬性 (屬於類,每個類一份)

  普通屬性 (屬於對象,每個對象一份)

  私有屬性 (屬於對象,跟普通屬性相似,只是不能通過對象直接訪問)

方法:(按作用)

  構造方法

  析構函數

方法:(按類型)

  普通方法

  私有方法(方法前面加兩個下劃線)

  靜態方法

  類方法

  屬性方法

靜態方法

@staticmethod
靜態方法,通過類直接調用,不需要創建對象,不會隱式傳遞self

類方法

@classmethod
類方法,方法中的self是類本身,調用方法時傳的值也必須是類的公有屬性,
就是說類方法只能操作類本身的公有字段

class Dog(object):
    food = "gutou"
    age = "1"
    def __init__(self, name):
        self.NAME = name
    @classmethod
    def eat(self,age): #只能是類中的變量
        # print(self.NAME)
        print(age)
        print(self.food)

    @classmethod
    def eat1(self, age):  # 只能是類中的變量
        # print(self.NAME)
        age = "2"
        self.food = "tang"
    @staticmethod
    def print_1():
        print(Dog.food, Dog.age)

d = Dog("labuladuo")
d.eat(Dog.age)    #通過對象調用
Dog.eat(Dog.age)  #通過類調用
print("-----1-----")
d.eat1(Dog.age)
Dog.print_1()
print("--------2-------")
Dog.eat1(Dog.age)
Dog.print_1()

屬性方法

屬性變為私有屬性,加斷言

class Cycle(object):
    def __init__(self,x,y,radius):
        self.x = x
        self.y = y
        self.radius = radius
    @property
    def radius(self):
        return self.__radius
    @radius.setter
    def radius(self,radius):
        assert radius > 0, "radius must be nonzero and non-negative"
        self.__radius = radius
    @radius.deleter
    def radius(self):
        del self.__radius
    def __str__(self):
        return "({0},{1},{2})".format(self.x,self.y,self.radius)

c = Cycle(1,1,7)
c.radius = 9
print(c)
del c.radius
print(c.radius)
#(1,1,9)
#AttributeError: ‘Cycle‘ object has no attribute ‘_Cycle__radius‘
class Dog(object):
    def __init__(self, name):
        self.name = name
        self.__food = None
    # def eat(self, food):原始方式
    #     self.__food = food
    #     print(‘%s eat %s‘ %(self.name, food))
    @property
    def eat(self):
        print(‘%s eat %s‘ %(self.name,self.__food))
    @eat.setter
    def eat(self, food):
        self.__food = food
    @eat.deleter
    def eat(self):
        del self.__food
        print("刪完了")


d = Dog("labuladuo")
# d.eat("baozi") #原始方式
d.eat
d.eat = "baozi"
d.eat  #調用方式沒變,只是改變傳入的參數就改變了結果
#可以刪除__food屬性

del d.eat
d.eat  # 報錯

‘‘‘輸出
labuladuo eat None
labuladuo eat baozi
刪完了
AttributeError: ‘Dog‘ object has no attribute ‘_Dog__food‘
‘‘‘

屬性方法應用場景

好吧,把一個方法變成靜態屬性有什麽卵用呢?既然想要靜態變量,那直接定義成一個靜態變量不就得了麽?well, 以後你會需到很多場景是不能簡單通過 定義 靜態屬性來實現的, 比如 ,你想知道一個航班當前的狀態,是到達了、延遲了、取消了、還是已經飛走了, 想知道這種狀態你必須經歷以下幾步:

1. 連接航空公司API查詢

2. 對查詢結果進行解析

3. 返回結果給你的用戶

因此這個status屬性的值是一系列動作後才得到的結果,所以你每次調用時,其實它都要經過一系列的動作才返回你結果,但這些動作過程不需要用戶關心, 用戶只需要調用這個屬性就可以,明白 了麽?

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


f = Flight("CA980")
f.flight_status

cool , 那現在我只能查詢航班狀態, 既然這個flight_status已經是個屬性了, 那我能否給它賦值呢?試試吧  

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

輸出為:發現不能更改

checking flight CA980 status
flight is arrived...
Traceback (most recent call last):
  File "/Users/jieli/PycharmProjects/python基礎/自動化day7面向對象高級/屬性方法.py", line 58, in <module>
    f.flight_status =  2
AttributeError: can‘t set attribute

當然可以改, 不過需要通過@proerty.setter裝飾器再裝飾一下,此時 你需要寫一個新方法, 對這個flight_status進行更改。  

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 = {
: "canceled",
:"arrived",
: "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 #觸發@flight_status.setter 
del f.flight_status #觸發@flight_status.deleter

  

  

  

  

python學習筆記8--面向對象--屬性和方法詳解