日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python对象基础

發布時間:2024/4/19 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python对象基础 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

定義操作

# 1. 定義類class Washer():def wash(self):print('我會洗?服')def print_info(self):# 類??獲取實例屬性print(f'haier1洗?機的寬度是{self.width}')print(f'haier1洗?機的?度是{self.height}')# 2. 創建對象 haier1 =Washer() # <__main__.Washer object at 0x0000018B7B224240> print(haier1) # haier1對象調?實例?法# 3. 添加實例屬性 haier1.width = 500 haier1.height = 800 # 4. 獲取實例的對象 print(f'haier1洗?機的寬度是{haier1.width}') print(f'haier1洗?機的?度是{haier1.height}')

魔法?法

在Python中, xx() 的函數叫做魔法?法,指的是具有特殊功能的函數

1. init()

注意

init() ?法,在創建?個對象時默認被調?,不需要?動調?

init(self) 中的self參數,不需要開發者傳遞,python解釋器會?動把當前的對象引?傳遞過去。

class Washer():# 定義初始化功能的函數 def __init__(self): # 添加實例屬性self.width = 500self.height = 800 def print_info(self): # 類??調?實例屬性 print(f'洗?機的寬度是{self.width}, ?度是{self.height}') haier1 = Washer() haier1.print_info()

2.帶參數的init()

?個類可以創建多個對象,傳參數對不同的對象設置不同的初始化屬性

class Washer():def __init__(self, width, height):self.width = widthself.height = heightdef print_info(self):print(f'洗?機的寬度是{self.width}')print(f'洗?機的?度是{self.height}') haier1 = Washer(10, 20) haier1.print_info() haier2 = Washer(30, 40) haier2.print_info()

3. str__()

當使?print輸出對象的時候,默認打印對象的內存地址。如果類定義了 str ?法,那么就會打印從在這個?法中 return 的數據。

class Washer():def __init__(self, width, height):self.width = widthself.height = heightdef __str__(self):return '這是海爾洗?機的說明書' haier1 = Washer(10, 20) # 這是海爾洗?機的說明書 print(haier1)

4.del()

當刪除對象時,python解釋器也會默認調? del() ?法。

class Washer():def __init__(self, width, height):self.width = widthself.height = heightdef __del__(self):print(f'{self}對象已經被刪除') haier1 = Washer(10, 20) # <__main__.Washer object at 0x0000026118223278>對象已經被刪除 del haier1

總結

    • 創建類

      class 類名():代碼
  • 對象

    對象名 = 類名()
  • 添加對象屬性

    • 類外面
    對象名.屬性名 =
    • 類??
    self.屬性名 =
  • 獲取對象屬性

    • 類外面
    對象名.屬性名
    • 類??
    self.屬性名
  • ? 魔法方法

    • init_() : 初始化

    • str__() :輸出對象信息

    • del() :刪除對象時調?

繼承

單繼承

# 1. 師?類 class Master(object):def __init__(self):self.kongfu = '[古法煎餅果?配?]'def make_cake(self):print(f'運?{self.kongfu}制作煎餅果?')# 2. 徒弟類 class Prentice(Master):pass # 3. 創建對象daqiu daqiu = Prentice() # 4. 對象訪問實例屬性 print(daqiu.kongfu) # 5. 對象調?實例?法 daqiu.make_cake()

多繼承

class Master(object):def __init__(self):self.kongfu = '[古法煎餅果?配?]'def make_cake(self):print(f'運?{self.kongfu}制作煎餅果?')# 創建學校類 class School(object):def __init__(self):self.kongfu = '[??煎餅果?配?]'def make_cake(self):print(f'運?{self.kongfu}制作煎餅果?') class Prentice(School, Master):pass daqiu = Prentice() print(daqiu.kongfu) daqiu.make_cake()

注意:當?個類有多個?類的時候,默認使?第?個?類的同名屬性和?法。

?類和?類具有同名屬性和?法,默認使??類的同名屬性和?法。

?類調??類的方法

class Master(object):def __init__(self):self.kongfu = '[古法煎餅果?配?]'def make_cake(self):print(f'運?{self.kongfu}制作煎餅果?')class School(object):def __init__(self):self.kongfu = '[??煎餅果?配?]'def make_cake(self):print(f'運?{self.kongfu}制作煎餅果?')class Prentice(School, Master):def __init__(self):self.kongfu = '[獨創煎餅果?配?]'def make_cake(self):# 如果是先調?了?類的屬性和?法,?類屬性會覆蓋?類屬性,故在調?屬性前,先調????類的初始化self.__init__()print(f'運?{self.kongfu}制作煎餅果?')# 調??類?法,但是為保證調?到的也是?類的屬性,必須在調??法前調??類的初始化def make_master_cake(self):Master.__init__(self)Master.make_cake(self)def make_school_cake(self):School.__init__(self)School.make_cake(self)def make_cake1(self):print(f'運?{self.kongfu}制作煎餅果?')# ?法2.1# super(School, self).__init__()# super(School, self).make_cake()# ?法2.2super().__init__()super().make_cake()daqiu = Prentice() daqiu.make_cake() daqiu.make_master_cake() daqiu.make_school_cake() daqiu.make_cake()

super方法

class Prentice(School, Master):def __init__(self):self.kongfu = '[獨創煎餅果?配?]'def make_cake(self):# 如果是先調?了?類的屬性和?法,?類屬性會覆蓋?類屬性,故在調?屬性前,先調????類的初始化self.__init__()print(f'運?{self.kongfu}制作煎餅果?')# 調??類?法,但是為保證調?到的也是?類的屬性,必須在調??法前調??類的初始化def make_master_cake(self):Master.__init__(self)Master.make_cake(self)def make_school_cake(self):School.__init__(self)School.make_cake(self)def make_cake1(self):print(f'運?{self.kongfu}制作煎餅果?')# ?法2.1# super(School, self).__init__()# super(School, self).make_cake()# ?法2.2super().__init__()super().make_cake()# ?次性調??類的同名屬性和?法# 注意:使?super() 可以?動查找?類。調?順序遵循 __mro__ 類屬性的順序。?較適合單繼承使?。def make_old_cake(self):# ?法?:代碼冗余;?類類名如果變化,這?代碼需要頻繁修改# Master.__init__(self)# Master.make_cake(self)# School.__init__(self)# School.make_cake(self)# ?法?: super()# ?法2.1 super(當前類名, self).函數()# super(Prentice, self).__init__()# super(Prentice, self).make_cake()# ?法2.2 super().函數()super().__init__()super().make_cake()

私有權限

在Python中,可以為實例屬性和?法設置私有權限,即設置某個實例屬性或實例?法不繼承給?類。

設置私有權限的?法:在屬性名和?法名 前? 加上兩個下劃線 __

私有屬性和私有?法只能在類??訪問和修改。

在Python中,?般定義函數名 get_xx ?來獲取私有屬性,定義 set_xx?來修改私有屬性值。

class Master(object): def __init__(self):self.kongfu = '[古法煎餅果?配?]' def make_cake(self):print(f'運?{self.kongfu}制作煎餅果?')class School(object): def __init__(self):self.kongfu = '[??煎餅果?配?]' def make_cake(self):print(f'運?{self.kongfu}制作煎餅果?')class Prentice(School, Master): def __init__(self):self.kongfu = '[獨創煎餅果?配?]'# 定義私有屬性self.__money = 2000000# 定義私有?法 def __info_print(self):print(self.kongfu)print(self.__money) def make_cake(self):self.__init__()print(f'運?{self.kongfu}制作煎餅果?') def make_master_cake(self):Master.__init__(self)Master.make_cake(self) def make_school_cake(self):School.__init__(self)School.make_cake(self) # 徒孫類 class Tusun(Prentice): pass daqiu = Prentice() # 對象不能訪問私有屬性和私有?法 # print(daqiu.__money) # daqiu.__info_print() xiaoqiu = Tusun() # ?類?法繼承?類的私有屬性和私有?法 # print(xiaoqiu.__money) # ?法訪問實例屬性__money # xiaoqiu.__info_print()

總結

  • 繼承的特點

    • ?類默認擁有?類的所有屬性和?法
    • ?類重寫?類同名?法和屬性
    • ?類調??類同名?法和屬性
  • super()?法快速調??類?法

  • 私有權限

    • 不能繼承給?類的屬性和?法需要添加私有權限
    • 語法
    class 類名():# 私有屬性__屬性名 =# 私有?法def __函數名(self):代碼

多態

類屬性

  • 類屬性就是 類對象 所擁有的屬性,它被 該類的所有實例對象 所共有
  • 類屬性可以使? 類對象實例對象 訪問

類屬性的優點

  • 類的實例 記錄的某項數據 始終保持?致時,則定義類屬性。

  • 實例屬性要求每個對象為其 單獨開辟?份內存空間 來記錄數據,? 類屬性 為全類所共有,僅占??份內存更加節省內存空間

## 類屬性和實例屬性 class Dog(object):tooth = 10 wangcai = Dog() xiaohei = Dog() print(Dog.tooth) # 10 print(wangcai.tooth) # 10 print(xiaohei.tooth) # 10

修改類屬性

類屬性只能通過類對象修改,不能通過實例對象修改,如果通過實例對象修改類屬性,表示的是創建了?個實例屬性。

class Dog(object):tooth = 10 wangcai = Dog() xiaohei = Dog()# 修改類屬性 Dog.tooth = 12 print(Dog.tooth) # 12 print(wangcai.tooth) # 12 print(xiaohei.tooth) # 12# 不能通過對象修改屬性,如果這樣操作,實則是創建了?個實例屬性 wangcai.tooth = 20 print(Dog.tooth) # 12 print(wangcai.tooth) # 20 print(xiaohei.tooth) # 12

實例屬性

class Dog(object):def __init__(self):self.age = 5def info_print(self):print(self.age) wangcai = Dog() print(wangcai.age) # 5 # print(Dog.age) # 報錯:實例屬性不能通過類訪問 wangcai.info_print() # 5

類?法和靜態?法

類?法特點

  • 第?個形參是類對象的?法
  • 需要?裝飾器 @classmethod 來標識其為類?法,對于類?法,第?個參數必須是類對象,?般以cls 作為第?個參數。

類?法使?場景

  • 當?法中 需要使?類對象 (如訪問私有類屬性等)時,定義類?法
  • 類?法?般和類屬性配合使?
class Dog(object):__tooth = 10@classmethoddef get_tooth(cls):return cls.__tooth wangcai = Dog() result = wangcai.get_tooth() print(result) # 10

靜態?法

靜態?法特點

  • 需要通過裝飾器 @staticmethod 來進?修飾,靜態?法既不需要傳遞類對象也不需要傳遞實例對象(形參沒有self/cls)

  • 靜態?法 也能夠通過 實例對象類對象 去訪問。

靜態?法使?場景

  • 當?法中 既不需要使?實例對象(如實例對象,實例屬性),也不需要使?類對象 (如類屬性、類?法、創建實例等)時,定義靜態?法
  • 取消不需要的參數傳遞**,有利于 **減少不必要的內存占?和性能消耗
class Dog(object):@staticmethoddef info_print():print('這是?個狗類,?于創建狗實例....') wangcai = Dog() # 靜態?法既可以使?對象訪問?可以使?類訪問 wangcai.info_print() Dog.info_print()

總結

類?法

@classmethod def xx():代碼

靜態?法

@staticmethod def xx():代碼

異常

常規寫法

try:可能發?錯誤的代碼 except:如果出現異常執?的代碼## 常規寫法 try:print(num) except NameError:print('有錯誤')## 捕獲異常描述信息 try:print(num) except (NameError, ZeroDivisionError) as result:print(result)## 捕獲所有異常 try:print(num) except Exception as result:print(result)## 異常的else ## else表示的是如果沒有異常要執?的代碼。 try:print(1) except Exception as result:print(result) else:print('我是else,是沒有異常的時候執?的代碼')## 異常的finally ## finally表示的是?論是否異常都要執?的代碼,例如關閉?件 try:f = open('test.txt', 'r') except Exception as result:f = open('test.txt', 'w') else:print('沒有異常,真開?') finally:f.close()

異常的傳遞

import time try:f = open('test.txt')try:while True:content = f.readline()if len(content) == 0:breaktime.sleep(2)print(content)except:# 如果在讀取?件的過程中,產?了異常,那么就會捕獲到# ?如 按下了 ctrl+cprint('意外終?了讀取數據')finally:f.close()print('關閉?件') except:print("沒有這個?件")

?定義異常

在Python中,拋出?定義異常的語法為 raise 異常類對象 。

# ?定義異常類,繼承Exception class ShortInputError(Exception):def __init__(self, length, min_len):self.length = lengthself.min_len = min_len# 設置拋出異常的描述信息def __str__(self):return f'你輸?的?度是{self.length}, 不能少于{self.min_len}個字符' def main():try:con = input('請輸?密碼:')if len(con) < 3:raise ShortInputError(len(con), 3)except Exception as result:print(result)else:print('密碼已經輸?完成') main()

總結

## 異常語法 try:可能發?異常的代碼 except:如果出現異常執?的代碼 else:沒有異常執?的代碼 finally:?論是否異常都要執?的代碼## 捕獲異常 except 異常類型:代碼 except 異常類型 as xx:代碼## ?定義異常 # 1. ?定義異常類 class 異常類類名(Exception):代碼# 設置拋出異常的描述信息def __str__(self):return ... # 2. 拋出異常 raise 異常類名() # 捕獲異常 except Exception...

模塊和包

模塊

Python 模塊(Module),是?個 Python ?件,以 .py 結尾,包含了 Python 對象定義和Python語句。

模塊能定義函數,類和變量,模塊?也能包含可執?的代碼。

導?模塊的?式

  • import 模塊名
  • from 模塊名 import 功能名
  • from 模塊名 import *
  • import 模塊名 as 別名
  • from 模塊名 import 功能名 as 別名
### import # 1. 導?模塊 import 模塊名 import 模塊名1, 模塊名2... # 2. 調?功能 模塊名.功能名()## from..import.. from 模塊名 import 功能1, 功能2, 功能3... from math import sqrt print(sqrt(9))## from .. import * from 模塊名 import * from math import * print(sqrt(9))### as定義別名 # 模塊定義別名 import 模塊名 as 別名 # 功能定義別名 from 模塊名 import 功能 as 別名

制作模塊

每個Python?件都可以作為?個模塊,模塊的名字就是?件的名字。也就是說?定義模塊名必須要符合標識符命名規則

## 新建?個Python?件,命名為 my_module1.py ,并定義 testA 函數。 def testA(a, b):print(a + b) # 只在當前?件中調?該函數,其他導?的?件內不符合該條件,則不執?testA函數調? if __name__ == '__main__':testA(1, 1)## 調?模塊 import my_module1 my_module1.testA(1, 1)

注意

  • 如果使? from … import … 或 from … import * 導?多個模塊的時候,且模塊內有同名功能。當調?這個同名功能的時候,調?到的是后?導?的模塊的功能。
  • all

    如果?個模塊?件中有 all 變量,當使? from xxx import * 導?時,只能導?這個列表中的元素。

    __all__ = ['testA']def testA():print('testA')def testB():print('testB')## 導?模塊的?件代碼 from my_module1 import * testA() testB()

    包將有聯系的模塊組織在?起,即放到同?個?件夾下,并且在這個?件夾創建?個名字為 init.py ?件,那么這個?件夾就稱之為包。

    新建包

    [New] — [Python Package] — 輸?包名 — [OK] — 新建功能模塊(有聯系的模塊)。

    注意:新建包后,包內部會?動創建 init.py ?件,這個?件控制著包的導??為。

    • 新建包 mypackage
    • 新建包內模塊: my_module1 和 my_module2
    • 模塊內代碼如下
    # my_module1 print(1) def info_print1():print('my_module1') # my_module2 print(2) def info_print2():print('my_module2')

    導?包

    ## import 包名.模塊名 ## 包名.模塊名.?標import my_package.my_module1 my_package.my_module1.info_print1()## 必須在 __init__.py ?件中添加 __all__ = [] ,控制允許導?的模塊列表。 from my_package import * my_module1.info_print1()

    達夢支持

    有任何問題請到技術社區反饋。

    24小時免費服務熱線:400 991 6599

    達夢技術社區:https://eco.dameng.com

    總結

    以上是生活随笔為你收集整理的Python对象基础的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。